How to run command-line or execute external application from Java
Java, Programming June 6th, 2007Have 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
Related post
- Get System Information on command-line mode Introduction There is a built-in command on Windows XP and Windows 2003 which can gather system configuration information to display...
Related posts:




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.
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
November 26th, 2008 at 9:58 pm
To John,
You can set the batch file to pause until you press any key by add ‘pause’ to the end of a batch file.
For example, “test.bat”
December 16th, 2008 at 1:13 pm
thanks linglom, you have been very helpful, another question. I want to interact with cmd from java, an example: supose you have a program in C with a “scanf();” line and i want to execute that program and interact with it from inside my java program.
I do this:
String cmd = ”cmd /c myCprogram.exe”;
p = Runtime.getRuntime().exec(cmd);
but it wont work because it will stay blocked expecting that i enter a value to the “scanf();”. How can i solve this???
PS. A batch file is too complicated because i dont always now how many “scanf();” will be in the C program.
December 31st, 2008 at 12:49 pm
linglom, your suggestions to John have been very helpful. I’ve tried applying your script recommendations but am having a small issue.
I have a series of SQL commands that are performed on a database table. This string is called within a batch file.
I would like to execute it within java. This is what I have written using your previous suggestions. String cmd[] = {“cmd”,”mysql -h host -u user -p pass clientexport<’c:\\generate.sql’”};
No errors are thrown but no updates take place. Am I just missing a step?
Thanks
January 11th, 2009 at 9:41 am
To John,
Your problem seems to be complicated. If you have to interact with external application many times in different way, it may not good to write application to interact with it. I think it’s hard to debug and maintain your application. I have better way. Try AutoIt, it is a tool to create script that interact with Windows GUI. It is easy to use. Let’s see it yourself – AutoIt v3.
To Harris,
I think the best way is to try to run the code outside the batch file first to test if the command is correctly or not.
March 9th, 2009 at 7:06 am
This is a very good topic,thanks linglom.
I was trying to copy files from one folder to another folder and it worked well.
But when i tried to execute a DOS del from Java, the program was hanged. I am sure that was because DOS command promt will ask for a confirmation before it does the delete :
Are you sure (Y/N):
Can you guys help me out? Thanks
Regards
March 9th, 2009 at 7:21 am
I’ve solved the problem by putting /Q (Quiet mode, do not ask if ok to delete on global wildcard) parameter for del command.
Process pr = rt.exec(“cmd /c del /Q C:\\Laser\\*.*”);
March 10th, 2009 at 9:45 pm
Hi, Kevin Do
Thanks for your sharing.
April 9th, 2009 at 11:25 am
hi
I am able to run DOS command from JAVA in following way
String fullPath = “cmd /c start D:\\tool\\citi\\bin\\properties\\build os “;
Runtime rt= Runtime.getRuntime();
try{
Process p=rt.exec(fullPath.toString());
}catch (Exception exception){
}
But now i want to close the command prompt window . How to do this. Please help me out ..
April 13th, 2009 at 10:03 pm
Hi, Nikhil
Try to modify the command by add “” after start command as the example below,
From:
cmd /c start “C:\Program Files\WinRAR\WinRAR.exe”
To:
cmd /c start “” “C:\Program Files\WinRAR\WinRAR.exe”
April 17th, 2009 at 4:44 pm
Hi Linglom,
It didnt worked.
is there any other way out to close the command propmp window .
Following is the command which am firing to open the command prompt
String fullPath = “cmd /c start D:\\tool\\citi\\bin\\properties\\build.bat /c ”
Runtime rt= Runtime.getRuntime();
Process p=rt.exec(fullPath.toString());
April 21st, 2009 at 1:42 pm
What if you remove the text “cmd /c start”?
String fullPath = “D:\\tool\\citi\\bin\\properties\\build.bat /c”
May 9th, 2009 at 3:38 am
i have to run this command in windows…
i have a folder containing two files named “a” and “b”
the command is
t2mf -r a b
how do i do that pls tell
May 9th, 2009 at 3:50 am
continued….
by cmd i m doing like this …
i m going inside that folder by cd commmand …
and typing this command
t2mf -r a b
where a is input file already existing and b is output file generated..
May 12th, 2009 at 9:41 am
Hi, Amit
Try to modify the code in the post.
“cmd /c t2mf -r a b”
June 9th, 2009 at 6:00 pm
thanks a lot for this article
i am planning to develop a playlist app for mplayer in linux using this techinque
Do you have articles on Qt development.
If yes , please send link to : driv10012004@yahoo.co.in
July 5th, 2009 at 10:28 am
Hi all, thanks for your advice; these comments have been very helpful to me. I am trying to get Java to run the following Mac OS X terminal command:
pdflatex /Users/username/Desktop/test.tex
That command successfully runs from the terminal to turn the .tex file into a .pdf.
I have used your strategies with
String[] cmd = new String[]{“open”,pathname};
Runtime rt = Runtime.getRuntime();
Process proc = rt.exec(cmd);
so that Java will for example successfully execute
open /Users/username/Desktop/test.pdf
but when I try to use pdflatex, I get the following error:
java.io.IOException: pdflatex: not found
at java.lang.UNIXProcess.forkAndExec(Native Method)
at java.lang.UNIXProcess.(UNIXProcess.java:52)
at java.lang.ProcessImpl.start(ProcessImpl.java:91)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:451)
at java.lang.Runtime.exec(Runtime.java:591)
at java.lang.Runtime.exec(Runtime.java:464)
Clearly, the pdflatex command is not supported by the runtime exec bit, but since both commands work as expected from the Terminal, I was wondering if you knew any way to instruct the Terminal directly to execute the command.
Thanks!
July 14th, 2009 at 6:40 am
Hi everybody,
I am executing a XOG utility like this on commmand line…
C:/MyWorks/xog -propertyfile test.properties
I am getting this output
—————————————-
Using https
Configuring context for TLS
———————————————————–
Clarity XML Open Gateway ( version: 12.0.1.5063 )
———————————————————–
Login Succeeded
Request Document: rsm_resources_read_xog1.xml
Writing output to Outputrsm_ShipraResource_read.xml
Request Succeeded
Logout Succeeded
———————————————–
But If I try the following code snippet
String [] cmdarray = {“D:/MyWorks/xog”, “-propertyfile”, “D:/MyWorks/test.properties”};
Then I get the below exception …
java.io.IOException: CreateProcess: D:\MyWorks\xog -propertyfile D:/MyWorks/test.properties error=193
at java.lang.ProcessImpl.create(Native Method)
at java.lang.ProcessImpl.(ProcessImpl.java:81)
at java.lang.ProcessImpl.start(ProcessImpl.java:30)
at java.lang.ProcessBuilder.start(ProcessBuilder.java:451)
at java.lang.Runtime.exec(Runtime.java:591)
at java.lang.Runtime.exec(Runtime.java:464)
at com.Test.main(Test.java:49)
I have tried with giving the extension to ‘xog’ command but it doesn’t help. I also have tried to run the resultant process string on the command line i.e.
D:\MyWorks\xog -propertyfile D:/myworks/test.properties
I get the following output
——————————-
Using https
Configuring context for TLS
———————————————————–
Clarity XML Open Gateway ( version: 12.0.1.5063 )
———————————————————–
No valid input files specified
Usage: xog
Arguments:
-username
-password
-servername
-portnumber
-input input
-output output
-propertyfile (used in place of any or all parameters above)
——————————————————
I think there is some problem with properties file. Process is not able to read that file while both files are same!!!
Can anybody help me?
Thanks.
August 30th, 2009 at 5:53 pm
Hello Linglom and All
Could you please help me about a java code which will run in windows for executing some shell script in Some Sun Machine?
Usually I telnet , input user name and password and run a script. I need to do it from my windows java application.
Thanks
August 31st, 2009 at 11:38 am
Hi, Ashikur Rahman
If you use telnet command, it will need to interact with a user. So I suggest you create a script which do your task first and then call the script from your java application later.
To create a script, you can try autoit which is a free software helps you to create scripts to automate tasks on Windows. See, AutoIt
September 1st, 2009 at 9:31 am
Hi linglom,
I tried to execute this
Process p = Runtime.getRuntime().exec(“cat ABCD.* > filejadi2.txt”);
BufferedReader in = new BufferedReader(new InputStreamReader(p.getInputStream()));
it is run but there isn’t result file (filejadi2.txt)
help me please.
thanks.
September 2nd, 2009 at 10:40 am
Hi, Sifa
Try with a basic command such as listing directory to see if there is any result or not.
November 23rd, 2009 at 12:50 am
Thanks for the nice article. I also found it extremely helpful!
December 9th, 2009 at 8:18 pm
Dear All,
This thread is very useful, but it misses one important issue that I was not able to find a solution for.
Does anybody know which default username is used by JVM when it runs the external shell scripts via Runtime.getRuntime().exec ?
Is there a way to set this username somewhere?
I’m trying to run an external script containing privileged system commands using sudo, but I have no idea which user I should give the privilege to…
Many thanks for your help.
December 21st, 2009 at 11:56 am
Very informative. Nice article.
January 6th, 2010 at 11:00 am
Hi, tokared
I’m not sure but I think it’s the same user as you run the java application.
If it is on Windows and you want to run the command as a specified user, I will use Runas command.
January 22nd, 2010 at 2:15 pm
Hi
This works fine for jobs that finish and give it’s feedback immidiately and then closes. But how shall I do it for jobs that run “for a while”, for example a “tar -tvf” to tape drive ?
February 5th, 2010 at 2:33 pm
Excellent and very helpful article, Linglom. Thank you for posting it. For me the comments may be even more helpful…
I have a similar problem as Kevin (above) but some of the os-agnostic applications I am launcing do not have a /q or “quite mode”. Is there any way to create a 2-way interactive process or thread?
I have the following:
String line="";
BufferedReader br;
br = new BufferedReader(new InputStreamReader(System.in));
StringBuffer s2 = new StringBuffer();
Runtime oShell = Runtime.getRuntime();
String oSysName = System.getProperty("os.name" );
if(oSysName.toUpperCase().startsWith("WIN")) {
// We need to make this OS Agnostic
line = "cmd.exe /c "+getPath(sCommand)+".cmd"; // Shell Out to Win32
} else { line = "/bin/sh -c "+getPath(sCommand); } // Shell to UNIX, Linux or MAC
String args[] = line.split("[ \t]+"); // tokenize the commandLine into an array for exec()
System.out.println("\n SHELL> Type any additional parameters, end with ^D (UNIX) or ^Z (Win32) + [Enter] \n\n");
do {
line = br.readLine();
if (line != null) { args = addArrayNode (args, line); }
} while (line != null);
System.out.print(" SHELL> Executing Command, Please Wait... ");
System.out.print("\n\n The Following String is being sent to "+oSysName+ " for processing:\n\t"+Arrays.toString(args));
Process oProc = oShell.exec(args); //Process Launcher
// create reader to get errors as a character stream from the child process...
final BufferedReader errorHandler =
new BufferedReader(new InputStreamReader(oProc.getErrorStream()));
// create reader to get standard output as a character stream from child process...
final BufferedReader outputHandler =
new BufferedReader(new InputStreamReader(oProc.getInputStream()));
Then I launch threads to capture and display the output. such as:
//Get and display the standard output produced by the child process...(for non-ERRORs)
Thread stdoutThread = new Thread() {
public void run() {
try { int l; String line;
for(l = 0; (line = outputHandler.readLine()) != null; ) {
if (line.length() > 0) { l++; outputLines.addElement(line); }
System.out.println(line);
}
if (l >0) System.out.print("\n\nRead " + l + " lines (above) from stdout.");
outputHandler.close();
} catch (IOException ie) { System.out.println("SHELL> IO exception on stdout: " + ie); }
}
};//end-sddoutThread-def
I’m having a hard time getting my head around the (interactive scenario’s) thread handler. How do I know if it needs a response? Which thread should I watch? Both? Maybe use: getOutputStream ???
not sure if my code snippits will be formatted properly, but any help would be greatly appreciated..
Joe
March 2nd, 2010 at 11:18 am
Helo, i’m beginner in java. How to run this coding in xml, bacauce i want to create web page that can execute this code. Anybody can give idea about this.
March 4th, 2010 at 10:06 pm
Hi, Aravin
You should use Java applet if you want to develop Java application on web.
March 5th, 2010 at 8:18 pm
Hi linglom,
I have following code:
String cm = ” rmdir /q /s ” + dir;
Process process = Runtime.getRuntime().exec(“cmd /c ” + cm);
int exitVal = process.waitFor();
If I try to run it from Eclipse, it executes well.
If I generate a (fat) jar from it, and start it from the
DOS window, it hangs forever.
Do you have any hint?
Cheers / Gabor
March 5th, 2010 at 9:50 pm
Hi,
I’ve found a solution in the meanwhile here:
http://www.javaworld.com/javaworld/jw-12-2000/jw-1229-traps.html?page=1
But thanks anyway for the great article & thread!
March 9th, 2010 at 12:20 am
Hi,
does anyone know how to run a cmd prompt with administrative privilleges through a java program?
Thanks in advance!
March 10th, 2010 at 10:43 pm
THanks for this article… Saved me a lot of time while making my Java app.
March 12th, 2010 at 9:24 am
Hi, Arnie
You can use runas command to run the command prompt as administrator but you need to specify password after run the command:
“runas /user:Administrator cmd”
Reference: Runas
March 12th, 2010 at 10:19 am
Hi linglom ,
I know this cmd but it doesn’t give you access if the “Administrator” account is not password protected and if it is or if you try the same cmd with other administrator account which supports a password , a new cmd prompt will appear but actually it doesn’t run as administrator, so this cmd doesn’t change anything (if you tried it you know what I m talking about)
But thanks for your interest!
March 31st, 2010 at 1:10 am
Hi Linglom,
I went into your program and i tried to relate this with my program . I want to run a simple script(contains some code) which is in text file and execute the output of that text in Java or any other language. How can i do that ? Please help me ,it’s really urgent.
April 7th, 2010 at 2:38 am
Respected Sir
I have a shell script(interactive_terrier.sh ) which when run should give the following output
Setting TERRIER_HOME to /home/student/terrier-3.0
Setting JAVA_HOME to /usr
INFO – Loading document lengths for document structure into memory
INFO – Structure meta reading lookup file into memory
INFO – Structure meta reading reverse map for key docno directly from disk
INFO – Structure meta loading data file into memory
INFO – time to intialise index : 0.417
Please enter your query:
waiting for the user to enter some query.
Now I want a java program to achieve the same thing by invoking this shell script. I wrote a java progr but this is the outpput that I recieve:
Setting TERRIER_HOME to /home/student/terrier-3.0
Setting JAVA_HOME to /usr
What could be the reason for this? Kindly help.
Regards
Saurabh
April 22nd, 2010 at 11:07 am
Hi Linglom,
how to execute other application(ex:snort,wireshark,metasploit) from java?
thanks for your help n_n
April 25th, 2010 at 11:12 pm
Hi, Dian
If a program has command line, or be able to run in background mode, it shouldn’t be any problem. Simply apply code from the post.
April 29th, 2010 at 1:31 pm
ThanQ very much.
These r very helpful to me.
May 21st, 2010 at 7:57 am
Hi,
I need to run a sas program from java.i dont need to access sas datasets/tables, but just run/execute a sas programCan someone help me what should be the code to do this?
Thanks,
Kiran
August 27th, 2010 at 2:00 pm
Hi,
I’m a java beginner. I need to run a fortran program from java in linux. Now, a little explanation how I’m doing it without java. I have 2 files in the same folder: test.inp and test.msh. Then a open a terminal in the same folder and give in the path of the executable (from the program) and the name of the executable and finally the filename: path_executable/name_executable test
Now I don’t no how to bring this in my exec.
Now I tried this
Runtime rt = Runtime.getRuntime();
String[] cmd = {“//home//newfolder//test”}; // this is the path of my folder
Process pr = rt.exec(“cmd/c path_executable/name_executable test
“); //this is the command
I don’t no what I’m doing wrong or how to manage it.
Can anyone give me some advices?