Execute command from java windows

How to Execute Operating System Commands in Java

Although Java is a cross-platform programming language, sometimes we need to access to something in an operating system dependent way. In other words, we need a Java program to call native commands that are specific to a platform (Windows, Mac or Linux). For example, querying hardware information such as processer ID or hard disk ID requires invoking a kind of native command provided by the operating system. Throughout this tutorial, you will learn how to execute a native command from within a Java program, including sending inputs to and getting outputs from the command.

Basically, to execute a system command, pass the command string to the exec() method of the Runtime class. The exec() method returns a Process object that abstracts a separate process executing the command. From the Process object we can get outputs from and send inputs to the command. The following code snippet explains the principle:

Now, let’s walk through some real code examples.

The following code snippet runs the ping command on Windows and captures its output:

It gives the following output in the standard console:

1. Getting Standard Output

Then invoke the readLine() method of the reader to read the output line by line, sequentially:

2. Getting Error Output

So it’s recommended to capture both the standard output and error output to handle both normal and abnormal cases.

3. Sending Input

Check the system clock, it is updated immediately.

4. Waiting for the process to terminate

Note that the waitFor() method returns an integer value indicating whether the process terminates normally (value 0) or not. So it’s necessary to check this value.

5. Destroying the process and checking exit value

NOTE: Using the waitFor() and exitValue() method is exclusive, meaning that either one is used, not both.

6. Other exec() methods

exec(String[] cmdarray)

This method is useful to execute a command with several arguments, especially arguments contain spaces. For example, the following statements execute a Windows command to list content of the Program Files directory:

For other exec() methods, consult the relevant Javadoc which is listed below.

API References:

Other Java File IO Tutorials:

About the Author:

Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He started programming with Java in the time of Java 1.4 and has been falling in love with Java since then. Make friend with him on Facebook and watch his Java videos you YouTube.

How to execute unix commands through Windows/cygwin using Java

I am trying to accomplish two things:

I am running cygwin on Windows7 to execute my unix shell commands and I need to automate the process by writing a Java app. I already know how to use the windows shell through Java using the ‘Process class’ and Runtime.getRuntime().exec(«cmd /c dir») . I need to be able to do the same with unix commands: i.e.: ls -la and so forth. What should I look into?

Is there a way to remember a shell’s state? explanation: when I use: Runtime.getRuntime().exec(«cmd /c dir») , I always get a listing of my home directory. If I do Runtime.getRuntime().exec(«cmd /c cd «) and then do Runtime.getRuntime().exec(«cmd /c dir») again, I will still get the listing of my home folder. Is there a way to tell the process to remember its state, like a regular shell would?

It seems that the bash command line proposed by Paŭlo does not work:

I am having trouble figuring out the technicalities.

This is my code:

line ends up having a null value.

I added this to my .bash_profile:

I added the following as well:

System Properties -> advanced -> Environment variables -> user variebales -> variable: BASH , value: c:\cygwin\bin

However, if I execute this instead, it works!

2 Answers 2

1. Calling unix commands:

You simply need to call your unix shell (e.g. the bash delivered with cygwin) instead of cmd .

should do. Of course, if your command is an external program, you could simply call it directly:

When starting this from Java, it is best to use the variant which takes a string array, as then you don’t have Java let it parse to see where the arguments start and stop:

The error message in your example ( ls: command not found ) seems to show that your bash can’t find the ls command. Maybe you need to put it into the PATH variable (see above for a way to do this from Java).

Maybe instead of /cygdrive/c/cygwin/bin , the right directory name would be /usr/bin .

(Everything is a bit complicated here by having to bridge between Unix and Windows conventions everywhere.)

The simple ls command can be called like this:

2. Invoking multiple commands:

There are basically two ways of invoking multiple commands in one shell:

  • passing them all at once to the shell; or
  • passing them interactively to the shell.

For the first way, simply give multiple commands as argument to the -c option, separated by ; or \n (a newline), like this:

Читайте также:  Lenovo t510i драйвера windows 10

or from Java (adapting the example above):

Here the shell will parse the command line as, and execute it as a script. If it contains multiple commands, they will all be executed, if the shell does not somehow exit before for some reason (like an exit command). (I’m not sure if the Windows cmd does work in a similar way. Please test and report.)

Instead of passing the bash (or cmd or whatever shell you are using) the commands on the command line, you can pass them via the Process’ input stream.

How to run command-line or execute external application from Java

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:

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/

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

Copy and Paste in Windows Command Prompt

96 Comments

Great 🙂 Helped me a lot 🙂 Thanks 🙂

How about executing a command from UNIX? i.e.
cat test.txt | mailx [email protected]
What does my string look like?

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

BufferedReader input = new BufferedReader(new InputStreamReader(pr.getInputStream()));

/*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.

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

Also please give me goodlink in java for developing software

How add a data into database using java

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.

Good article. Can you give suggestions for remote login using java programs.

Yo!
Wasjust serfing on net and found this site…want to say thanks. Great site and content!

This helped me a lot…

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.

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?

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.

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=”[email protected]”;
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

Hello, Thomas.
Thanks for your sharing.

Very Helpful! Thanks.

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.

“/c” is a parameter of cmd command. Why it doesn’t available?
So what exactly do you want to do with gdb debugger?

thanks for posting….i want to debug a C file from a java application.

But when I interact with gdb like this from java:

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?

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.

thanks for the tip linglom, i wrote the commands in a .txt file and used the -x command, like this:

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.

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”

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.

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 linglom January 11, 2009

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.

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

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\\*.*”);

Hi, Kevin Do
Thanks for your sharing.

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 ..

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”

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());

What if you remove the text “cmd /c start”?

String fullPath = “D:\\tool\\citi\\bin\\properties\\build.bat /c”

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

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..

Hi, Amit
Try to modify the code in the post.
“cmd /c t2mf -r a b”

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 : [email protected]

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:

That command successfully runs from the terminal to turn the .tex file into a .pdf.

I have used your strategies with

Runtime rt = Runtime.getRuntime();

Process proc = rt.exec(cmd);

so that Java will for example successfully execute

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.

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
———————————————–

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?

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.

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

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.

Hi, Sifa
Try with a basic command such as listing directory to see if there is any result or not.

Thanks for the nice article. I also found it extremely helpful!

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.

Very informative. Nice article.

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.

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 ?

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..

Читайте также:  Windows рабочий стол структура настройка
Оцените статью