| How to run command-line or execute external application from Java |
Have you ever confront a situation that you need to execute external programs while developing a Java application? For instance, you are developing a Java application and need to execute external application(another executable program) in the middle of the program or you may need to execute some commands such as listing directory command: dir (in windows) or ls (in Unix) while developing the program.
The following will show you how to execute the external program from Java application.
Example
Note: The example will use NetBeans as IDE.
Let see the example Java source code below:
import java.io.*; public class Main { public static void main(String args[]) { try { Runtime rt = Runtime.getRuntime(); //Process pr = rt.exec("cmd /c dir"); Process pr = rt.exec("c:\\helloworld.exe"); BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream())); String line=null; while((line=input.readLine()) != null) { System.out.println(line); } int exitVal = pr.waitFor(); System.out.println("Exited with error code "+exitVal); } catch(Exception e) { System.out.println(e.toString()); e.printStackTrace(); } } }
The above Java’s code will try to execute the external program (helloworld.exe) and show output in console as exit code of the external program.
The sample external program, Helloworld.exe (Visual Basic)

Code Explanation:
Runtime rt = Runtime.getRuntime(); Process pr = rt.exec("c:\\helloworld.exe");
Create Runtime Object and attach to system process. In this example, execute the helloworld.exe.
If you want to execute some commands, just modify the string in the rt.exec(“….�?) to command that you want.
For instance, in the comment line; //Process pr = rt.exec(”cmd /c dir”);
Note: that you need to enter “cmd /c …�? before type any command in Windows.
int exitVal = pr.waitFor(); System.out.println("Exited with error code "+exitVal);
Method waitFor() will make the current thread to wait until the external program finish and return the exit value to the waited thread.
Output example
Process pr = rt.exec(”c:\\helloworld.exe”);

Process pr = rt.exec(”cmd /c dir”);

Summary
This is a simple code to execute external applications. If you want to call functions from other program (ex. C++, Visual Basic DLL), you need to use JNI (Java Native Interface) which you can find a nice tutorial at codeproject.com.
If you need more information, below are some sites that talk about executing external code.
For Java users
- Execute an external program - Real’s Java How-to.
http://www.rgagnon.com/javadetails/java-0014.html - When Runtime.exec() won’t - Java World.
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html - Trouble with Runtime.getRuntime().exec(cmd) on Linux - Java.
http://www.thescripts.com/forum/thread16788.html - Runtime.getRuntime().exec (Linux / UNIX forum at JavaRanch).
http://saloon.javaranch.com/cgi-bin/ubb/ultimatebb.cgi?ubb=get_topic&f=13&t=001755 - Java’s Runtime.exec() and External Applications.
http://www.ensta.fr/~diam/java/online/io/javazine.html
For C++ users
- How can I start a process?
http://www.codeguru.com/forum/showthread.php?t=302501 - Executing programs with C(Linux).
http://www.gidforums.com/t-3369.html
























August 15th, 2007 at 4:14 pm
Great
Helped me a lot
Thanks 
September 22nd, 2007 at 4:25 am
How about executing a command from UNIX? i.e.
cat test.txt | mailx xxx@yahoo.com
What does my string look like?
September 24th, 2007 at 10:57 pm
As from your string, you do not need output line so you can comment out the while loop that print output and if I reference from the source code in my post, the code will look like
try {
Runtime rt = Runtime.getRuntime();
String[] cmd = {”/bin/bash”,”-c”,”cat test.txt | mailx test@test.com“};
Process pr = rt.exec(cmd);
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line=null;
/*while((line=input.readLine()) != null) {
System.out.println(line);
}*/
int exitVal = pr.waitFor();
System.out.println(”Exited with error code” +exitVal);
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
If you want more information, try to follows the links that I’ve just added at the bottom of the post.
November 29th, 2007 at 6:05 pm
I’m a java beginner,I have an error that on running java using editplus&jdk1.6.0_02 version cannot disply output.What I can do
November 29th, 2007 at 6:07 pm
Also please give me goodlink in java for developing software
November 29th, 2007 at 6:09 pm
How add a data into database using java
December 1st, 2007 at 8:44 am
To Mubarak,
1. What is your error message?
2. If you are a beginner, I recommends text book “Core Java 2, Volume I–Fundamentals”. You can find one at amazon.com
3. That depends on which database you are using.
Next time, please don’t separate comment.
February 7th, 2008 at 8:15 pm
Good article. Can you give suggestions for remote login using java programs.
February 8th, 2008 at 5:04 am
thanks a lot…
April 1st, 2008 at 4:54 am
Yo!
Wasjust serfing on net and found this site…want to say thanks. Great site and content!
June 5th, 2008 at 1:52 pm
Hi,
This helped me a lot…
June 13th, 2008 at 11:15 am
Hey Linglom,
Nice article. Helped me a lot. Thx!
I’m kind of new to the topic, and would really appreciate if you did a comment on how to use the outputstream for a process.
- OMG
June 14th, 2008 at 10:59 pm
Hi,
My Java class will execute the linux CAT command to join files as:
Process p = Runtime.getRuntime().exec(”cat a.txt b.txt > e.txt”);
I always receive error:
cat: >: No such file or directory
Note: a.txt and b.txt is existed.
Could anyone help me?
Thanks,
Ringo
June 18th, 2008 at 3:37 am
I would Just like to say that this has been gloriously helpful to me today, and that I very much appreciate you for helping out the general community.
August 6th, 2008 at 3:03 pm
Very helpful linglom, thanks.
Here is an example that sends an email, where the body of the mail is in a text file.
static private void remote_call_11 () {
System.out.println(”\nstatic private void remote_call_11 ()” );
try {
Runtime rt = Runtime.getRuntime();
String subject=” TestSubject11″;
String pipeFile=”/tmp/test2.out | “;
String email=”abc@xzy.net”;
String cmdline=”cat ” + pipeFile + ” mail -s ” + subject + ” “+email;
String[] cmd = {”/bin/bash”,”-c”,cmdline};
Process pr = rt.exec(cmd);
BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));
int exitVal = pr.waitFor();
System.out.println(”Exited with error code ” +exitVal);
} catch(Exception e) {
System.out.println(e.toString());
e.printStackTrace();
}
} // remote_call_11
August 10th, 2008 at 8:14 pm
Hello, Thomas.
Thanks for your sharing. Really appreciate.
October 31st, 2008 at 6:23 pm
Very Helpful! Thanks.
November 17th, 2008 at 11:35 pm
do you know a way to interact with cmd without “/c”.
Im asking this because im trying to interact with gdb debugger, but the /c command its not available so i cant pass my arguments correctly.
thanks
November 18th, 2008 at 9:00 pm
Hi, John
“/c” is a parameter of cmd command. Why it doesn’t available?
So what exactly do you want to do with gdb debugger?
November 19th, 2008 at 5:07 am
thanks for posting….i want to debug a C file from a java application.
But when I interact with gdb like this from java:
String cm[] = {”gdb”,”file C:/programm.exe”,”run”};
p = Runtime.getRuntime().exec(cm);
i cant because everything passed after gdb is passed like arguments so i get an error, and i cant use the “/c” or “&&” comand i would use with cmd to pass multiple commands.
Basically i want to debug a C file from java.
Do you know any tip?
November 19th, 2008 at 8:18 pm
Is it possible to put your gdb parameters after /c command?
Like this, pr = rt.exec(”cmd /c gdb …your gdb parameter goes here…”);
If it doesn’t work, what about batch (.bat) file. Write the gdb command in the batch file. I have provide some links in the summary section. Some of them has example about batch file.
November 20th, 2008 at 5:33 am
thanks for the tip linglom, i wrote the commands in a .txt file and used the -x command, like this:
String cmd[] = {”cmd”,”/c”,”gdb -batch C:/codigo.exe -x C:/orden.txt”};
p = Runtime.getRuntime().exec(cmd);
BUT I GOT AN ISSUE….WHEN I EXECUTE THE JAVA PROGRAM, A CONSOLE WINDOW APPEARS VERY QUICKLY, JUST LIKE THE ONE THAT APPEARS WHEN YOU USE GDB FROM COMMAND LINE, IT CLOSES VERY FAST BUT IN THE END IT APPEARS, IS THERE A WAY TO OBVIATE THIS EVENT.
thanks