- Execute windows commands from java
- Runtime.exec()
- Executing a Command from String
- Specify the Working Directory
- Using Environment Variables
- Running .bat and .sh Files
- ProcessBuilder
- ProcessBuilder: Executing Command from Strings
- ProcessBuilder: Specify the Working Directory
- ProcessBuilder: Environment Variables
- ProcessBuilder: Running .bat and .sh Files
- Conclusion
- How to Execute Operating System Commands in Java
- 1. Getting Standard Output
- 2. Getting Error Output
- 3. Sending Input
- 4. Waiting for the process to terminate
- 5. Destroying the process and checking exit value
- 6. Other exec() methods
- API References:
- Other Java File IO Tutorials:
- About the Author:
- How to execute cmd commands via Java
- 11 Answers 11
- How to execute shell command from Java
- 1. ProcessBuilder
- 2. Runtime.getRuntime().exec()
- 3. PING example
- 4. HOST Example
- References
- mkyong
Execute windows commands from java
In this article, we’ll take a look at how we can leverage the Runtime and ProcessBuilder classes to execute shell commands and scripts with Java.
We use computers to automate many things in our daily jobs. System administrators run many commands all the time, some of which are very repetitive and require minimal changes in-between runs.
This process is also ripe for automation. There’s no need to run everything manually. Using Java, we can run single or multiple shell commands, execute shell scripts, run the terminal/command prompt, set working directories and manipulate environment variables through core classes.
Runtime.exec()
The Runtime class in Java is a high-level class, present in every single Java application. Through it, the application itself communicates with the environment it’s in.
By extracting the runtime associated with our application via the getRuntime() method, we can use the exec() method to execute commands directly or run .bat / .sh files.
The exec() method offers a few overloaded variations:
- public Process exec(String command) — Executes the command contained in command in a separate process.
- public Process exec(String command, String[] envp) — Executes the command , with an array of environment variables. They’re provided as an array of Strings, following the name=value format.
- public Process exec(String command, String[] envp, File dir) — Executes the command , with the specified environment variables, from within the dir directory.
- public Process exec(String cmdArray[]) — Executes a command in the form of an array of Strings.
- public Process exec(String cmdArray[], String[] envp) — Executes a command with the specified environment variables.
- public Process exec(String cmdarray[], String[] envp, File dir) — Executes a command, with the specified environment variables, from within the dir directory.
It’s worth noting that these processes are run externally from the interpreter and will be system-dependent.
What’s also worth noting is the difference between String command and String cmdArray[] . They achieve the same thing. A command is broken down into an array anyway, so using any of these two should yield the same results.
It’s up to you to decide whether exec(«dir /folder») or exec(new String[] <"dir", "/folder">is what you’d like to use.
Let’s write up a few examples to see how these overloaded methods differ from each other.
Executing a Command from String
Let’s start off with the simplest approach out of these three:
Running this code will execute the command we’ve supplied in String format. However, we don’t see anything when we run this.
To validate if this ran correctly, we’ll want to get ahold of the process object. Let’s use a BufferedReader to take a look at what’s going on:
Now, when we run this method after the exec() method, it should yield something along the lines of:
Keep in mind that we’ll have to extract the process information from the Process instances as we go through other examples.
Specify the Working Directory
If you’d like to run a command from, say, a certain folder, we’d do something along the lines of:
Here, we’ve provided the exec() method with a command , a null for new environment variables and a new File() which is set as our working directory.
The addition of cmd /c before a command such as dir is worth noting.
Since I’m working on Windows, this opens up the cmd and /c carries out the subsequent command. In this case, it’s dir .
The reason why this wasn’t mandatory for the ping example, but is mandatory for this example is nicely answered by an SO user.
Running the previous piece of code will result in:
Let’s take a look at how we could supply the previous command in several individual parts, instead of a single String:
Running this piece of code will also result in:
Ultimately, regardless of the approach — using a single String or a String array, the command you input will always be broken down into an array before getting processed by underlying logic.
Which one you’d like to use boils down just to which one you find more readable.
Using Environment Variables
Let’s take a look at how we can use environment variables:
We can supply as many environment variables as we’d like within the String array. Here, we’ve just printed the value of var1 using echo .
Running this code will return:
Running .bat and .sh Files
Sometimes, it’s just much easier to offload everything into a file and run that file instead of adding everything programmatically.
Depending on your operating system, you’d use either .bat or .sh files. Let’s create one with the contents:
Then, let’s use the same approach as before:
This’ll open up the command prompt and run the .bat file in the working directory we’ve set.
Running this code surely enough results in:
With all of the overloaded exec() signatures taken care of, let’s take a look at the ProcessBuilder class and how we can execute commands using it.
ProcessBuilder
ProcessBuilder is the underlying mechanism that runs the commands when we use the Runtime.getRuntime().exec() method:
JavaDocs for the Runtime class
Taking a look at how the ProcessBuilder takes our input from the exec() method and runs the command, gives us a good idea of how to use it as well.
It accepts a String[] cmdarray , and that’s enough to get it running. Alternatively, we can supply it with optional arguments such as the String[] envp and File dir .
Let’s explore these options.
ProcessBuilder: Executing Command from Strings
Instead of being able to provide a single String, such as cmd /c dir , we’ll have to break it up in this case. For example, if we wanted to list the files in the C:/Users directory like before, we’d do:
To actually execute a Process , we run the start() command and assign the returned value to a Process instance.
Running this code will yield:
However, this approach isn’t any better than the previous one. What’s useful with the ProcessBuilder class is that it’s customizable. We can set things programmatically, not just via commands.
ProcessBuilder: Specify the Working Directory
Instead of supplying the working directory via the command, let’s set it programmatically:
Here, we’ve set the working directory to be the same as before, but we’ve moved that definition out of the command itself. Running this code will provide the same result as the last example.
ProcessBuilder: Environment Variables
Using ProcessBuilder s methods, it’s easy to retrieve a list of environment variables in the form of a Map . It’s also easy to set environment variables so that your program can use them.
Let’s get the environment variables currently available and then add some for later use:
Here, we’ve packed the returned environment variables into a Map and ran a forEach() on it to print out the values to our console.
Running this code will yield a list of the environment variables you have on your machine:
Now, let’s add an environment variable to that list and use it:
Running this code will yield:
Of course, once the program has finished running, this variable will not stay in the list.
ProcessBuilder: Running .bat and .sh Files
If you’d like to run a file, again, we’d just supply the ProcessBuilder instance with the required information:
Running this code results in the command prompt opening up and executing the .bat file:
Conclusion
In this article, we’ve explored examples of running shell commands in Java. We’ve used the Runtime and ProcessBuilder classes to do this.
Using Java, we can run single or multiple shell commands, execute shell scripts, run the terminal/command prompt, set working directories and manipulate environment variables through core classes.
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 cmd commands via Java
I am trying to execute command line arguments via Java. For example:
The above opens the command line but does not execute cd or dir . Any ideas? I am running Windows XP, JRE6.
(I have revised my question to be more specific. The following answers were helpful but do not answer my question.)
11 Answers 11
The code you posted starts three different processes each with it’s own command. To open a command prompt and then run a command try the following (never tried it myself):
I found this in forums.oracle.com
Allows the reuse of a process to execute multiple commands in Windows: http://kr.forums.oracle.com/forums/thread.jspa?messageID=9250051
You need something like
If you want to run several commands in the cmd shell then you can construct a single command like this:
Every execution of exec spawns a new process with its own environment. So your second invocation is not connected to the first in any way. It will just change its own working directory and then exit (i.e. it’s effectively a no-op).
If you want to compose requests, you’ll need to do this within a single call to exec . Bash allows multiple commands to be specified on a single line if they’re separated by semicolons; Windows CMD may allow the same, and if not there’s always batch scripts.
As Piotr says, if this example is actually what you’re trying to achieve, you can perform the same thing much more efficiently, effectively and platform-safely with the following:
You do not use «cd» to change the directory from which to run your commands. You need the full path of the executable you want to run.
Also, listing the contents of a directory is easier to do with the File/Directory classes
Each of your exec calls creates a process. You second and third calls do not run in the same shell process you create in the first one. Try putting all commands in a bat script and running it in one call: rt.exec(«cmd myfile.bat»); or similar
This because every runtime.exec(..) returns a Process class that should be used after the execution instead that invoking other commands by the Runtime class
If you look at Process doc you will see that you can use
on which you should work by sending the successive commands and retrieving the output..
Writing to the out stream from the process is the wrong direction. ‘out’ in that case means from the process to you. Try getting/writing to the input stream for the process and reading from the output stream to see the results.
As i also faced the same problem and because some people here commented that the solution wasn’t working for them, here’s the link to the post where a working solution has been found.
Also see the «Update» in the best answer for using Cygwin terminal
How to execute shell command from Java
In Java, we can use ProcessBuilder or Runtime.getRuntime().exec to execute external shell command :
1. ProcessBuilder
2. Runtime.getRuntime().exec()
3. PING example
An example to execute a ping command and print out its output.
4. HOST Example
Example to execute shell command host -t a google.com to get all the IP addresses that attached to google.com. Later, we use regular expression to grab all the IP addresses and display it.
P.S “host” command is available in *nix system only.
References
mkyong
I used the same (similar) code for my ShellWrapper. When I use commands like echo it works fine, but when I use commands like cat it returns an empty String….
can you please share your code using LS EAT AND Cat please
processBuilder.command(“bash”, “-c”, “cat /home/mkyong/web.log”);
processBuilder.command(“bash”, “-c”, “cat /home/mkyong/web.log”);
works fine, but when I pipe a string to Java process, then the
processBuilder.command(“bash”, “-c”, “cat /dev/stdin”);
I am trying to convert avro to json file through java, But it is not working
String output = obj.executeCommand(“java -jar /Users/xyz/Desktop/1server/jboss-as-7.1.1.Final/standalone/deployments/Command.war/WEB-INF/lib/avro-tools-1.7.7.jar tojson /Users/xyz/Desktop/avro/4.avro > /Users/xyz/Desktop/avro/D8EC9CC2A3E049648AFD4309B29D2A0F/4.json”);
But this is not working through java file,
I ran same command through terminal, avro is converted to json
Can you help me to run “java -jar * ” command
Did you find the solution for this ?
As a good practice, I wouldn’t catch Exception e. Just mention the two that need to be dealt with (IOException, InterruptedException) .
Why commands with pattern don’t work? Example: uptime | sed “s/^.* up \+\(.\+\), \+3 user.*$/\1/”
I am not able to execute stat command while fetching date of the file in Java code
I want to connect to DB in unix using java application and i have requirement while trying to connect with go to some specific location and then run java connection code ?
Coudl you please help me on this ?
I am trying to run a python script but it gives me error even if works in the terminal i am running from terminal in the same directory with java what problem can be it says file not found but it works in terminal
i want to write a java class which will be deployed on a server .java class has to perform
1.listing out docker containers and login to particular docker image.
2.after logging it has to execute two commands in docker image
can anyone please help
I try to run a bat file which contain a “pause” command, that lock the java thread.
I need to execute a custom unix command to run a process and it will take around 10sec for the process to run. How to do it.
The Process.waitFor() statement should instead be invoked after the BufferedReader finishes reading the input stream of the Process. This fixes an issue I am having here: the program stucks and never returns but the actual command in my Mac Terminal exits within a second.
Another tip is that it is better to use Process.waitFor(long, TimeUnit) to prevent that the Java program hangs.
I also find that I will need to have Process.waitFor() statement invoked BEFORE the BufferedReader reads the input stream of the Process if I have BufferedReader.ready() added.
As an additional remark, using Process.waitFor(long, TimeUnit) isn’t the complete solution. In my case, the command never returns and it does not print anything in Terminal.
In this case, the BufferedReader.readLine() causes the program to hang. It seems that adding an if condition to check BufferedReader.ready() before BufferedRader.readLine() can solve the issue.
I want to execute 2 commands in a sequence.
1. cd D://
2. java -jar -role hub
I tried below code but it tries to execute jar file first and then cd :
ProcessBuilder builder = new ProcessBuilder(“cmd”,”/c”,”start”,”cmd.exe”,”/K”, “java -jar -role hub && cd \”D:\\””);
builder.redirectErrorStream(true);
Process p = builder.start();
any suggestion for first cd should get execute and then .jar?
please read D://foldername and java -jar jarFile
Where do I download the shell package?
To your own machine. lol
let’s say we type ‘mysql’ in command prompt.
c:mysql
then the prompt changes to:
mysql>
now in this we type sql commands.
Can we achieve/automate this with java?
The article would be even better with a note on how to run a shell file sitting in the resources directory.
Thanks for the jump start anyway !
I really like your articles on Java. For this one i guess i could not do as mentioned. I googled and figured out that you need to first connect to the linux box from java and then you can execute shell commands. I could not make the Linux commands run from Java which is on Windows using this code.
Hi How can we add Timeout ?
If I want to check my java version on Mac, I used the “PING” example and replaced the command string with my value i.e. String command = “java -version”;
but the command does not get executed at all. Can you please let me know what am I missing?
Mkyong your tutorials are always straight to the point, bravo.
Hi I am trying to create a Terminal Emulator for Linux using Java… Can you help me by giving a direction..
Thanks in advance…
Access denied. Option -c requires administrative privileges. —-how to fix admin issue on windows 8.1
ok i got it had to read -n yea, thanks
Using array parameter is better, because…when some parameter has blank ( ex. “ABC DE” ) it will be treated as 2 parameters…
Array parameter is more safe… рџ™‚
Sorry…english is not my mother tongue…
The following code allows you to set a timer, restart the timer on keywords, and specify if you want it to be sent to your log or not. This prevents several problems I’ve run into while programming on the command line.
The method is complex, very complex, but it works well and avoids loops in favor of waiting for a synchronized notification whenever possible. It uses three threads. The main thread launches the application and waits. The reader thread processes whatever comes out of the application. The watchdog thread monitors for timeout and gets kicked by the reader thread to restart the timer whenever a keyword is detected.
public String timeoutValueCheckingShellCommand(final String[] cmd, final String[] restartTimerKeywords, final int timeout,final boolean logLevel2) <
StringBuilder sb = new StringBuilder();
ProcessBuilder p = new ProcessBuilder(cmd);
final Process process = p.start();
TimeoutLogger is a place to hold a common object for use through
the various threads. It is used for logging of data, locking the
main thread on the processRunning object, timeout status and
monitoring of if the thread is alive or not.
TimeoutLogger(boolean realtime,Process p)<
private final StringBuilder log = new StringBuilder();
AtomicBoolean timedOut = new AtomicBoolean(false);
AtomicBoolean isRunning = new AtomicBoolean(true);
final Object isRunningLock=new Object();
AtomicBoolean isLogging = new AtomicBoolean(true);
final Object isLoggingLock=new Object();
final Process processRunning;
final Timer watchDogTimer = new Timer(timeout, new ActionListener() <
public void actionPerformed(ActionEvent evt) <
Log.level4Debug(“Watchdog Triggered! Command timed out.”);
synchronized void log(char c)<
for (String check:restartTimerKeywords)<
if (logstring.endsWith(check) && isRunning.get())<
Log.level4Debug(“Timer Reset on keyword “+check);
synchronized String get()<
final TimeoutLogger tl = new TimeoutLogger(logLevel2,process);
/*if the watchDogtimer elapses, the timedOut boolean is set true
and the processRunning object is notified to release main process
/*notify the processRunning object when the thread is complete to
release the lock.
Thread processMonitor = new Thread(new Runnable() <
public void run() <
Log.level4Debug(“Process Monitor done.”);
> catch (InterruptedException ex) <
Logger.getLogger(Shell.class.getName()).log(Level.SEVERE, null, ex);
processMonitor.setName(“Monitoring Process Exit Status from ” + cmd[0]);
reads the output and restarts the timer if required.
Thread reader = new Thread(new Runnable() <