- 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:
- The Best Way to Execute Command Line in Java — Tips and Best Practices
- Using the .exec() method of the Runtime class
- Using ProcessBuilder
- Command Line Arguments in Java
- Using the Process class
- Passing command-line arguments
- Running a process from a different directory
- Other helpful code examples for executing command line in Java
- Conclusion
How to Execute Operating System Commands in Java
This Java File IO tutorial guides you how to write Java code to run native commands of the host operating system.
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:
String command = "command of the operating system"; Process process = Runtime.getRuntime().exec(command); // deal with OutputStream to send inputs process.getOutputStream(); // deal with InputStream to get ordinary outputs process.getInputStream(); // deal with ErrorStream to get error outputs process.getErrorStream();
The following code snippet runs the ping command on Windows and captures its output:
String command = «ping www.codejava.net»; try < Process process = Runtime.getRuntime().exec(command); BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) < System.out.println(line); >reader.close(); > catch (IOException e)
Pinging codejava.net [198.57.151.22] with 32 bytes of data: Reply from 198.57.151.22: bytes=32 time=227ms TTL=51 Reply from 198.57.151.22: bytes=32 time=221ms TTL=51 Reply from 198.57.151.22: bytes=32 time=220ms TTL=51 Reply from 198.57.151.22: bytes=32 time=217ms TTL=51 Ping statistics for 198.57.151.22: Packets: Sent = 4, Received = 4, Lost = 0 (0% loss), Approximate round trip times in milli-seconds: Minimum = 217ms, Maximum = 227ms, Average = 221ms
1. Getting Standard Output
For system commands that produce some output as result, we need to capture the output by creating a BufferedReader that wraps the InputStream returned from the Process :
BufferedReader reader = new BufferedReader( new InputStreamReader(process.getInputStream()));
Then invoke the readLine() method of the reader to read the output line by line, sequentially:
String line; while ((line = reader.readLine()) != null) < System.out.println(line); >reader.close();
Scanner scanner = new Scanner(process.getInputStream()); scanner.useDelimiter("\r\n"); while (scanner.hasNext()) < System.out.println(scanner.next()); >scanner.close();
2. Getting Error Output
A command is not always executed successfully, because there would be a case in which the command encounters an error. And typically, error messages are sent to the error stream. The following code snippet captures the error input stream returned by the Process :
BufferedReader errorReader = new BufferedReader( new InputStreamReader(process.getErrorStream())); while ((line = errorReader.readLine()) != null) < System.out.println(line); >errorReader.close();
So it’s recommended to capture both the standard output and error output to handle both normal and abnormal cases.
3. Sending Input
For interactive system commands which need inputs, we can feed the inputs for the command by obtaining the OutputStream returned by the Process . For example, the following code snippet attempts to change system date on Windows to 09-20-14 (in mm-dd-yy format):
String command = «cmd /c date»; try < Process process = Runtime.getRuntime().exec(command); BufferedWriter writer = new BufferedWriter( new OutputStreamWriter(process.getOutputStream())); writer.write("09-20-14"); writer.close(); BufferedReader reader = new BufferedReader(new InputStreamReader( process.getInputStream())); String line; while ((line = reader.readLine()) != null) < System.out.println(line); >reader.close(); > catch (IOException e)
The current date is: Sat 09/20/2014 Enter the new date: (mm-dd-yy) 09-20-14
4. Waiting for the process to terminate
For long-running command (e.g. batch script), we can make the calling thread to wait until the process has terminated, by invoking the waitFor() method on the Process object. For example:
int exitValue = process.waitFor(); if (exitValue != 0)
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
It’s recommend to destroy the process and checking its exit value to make sure the system command’s process is executed successfully and exited normally. For example:
process.destroy(); if (process.exitValue() != 0)
NOTE: Using the waitFor() and exitValue() method is exclusive, meaning that either one is used, not both.
6. Other exec() methods
Beside the primarily used method exec(String command) , the Runtime class also has several overloaded ones. Notably this one:
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:
String commandArray[] = ; Process process = Runtime.getRuntime().exec(commandArray);
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.
The Best Way to Execute Command Line in Java — Tips and Best Practices
Learn the best way to execute command line in Java and explore helpful tips and best practices. Discover the differences between .exec() method, ProcessBuilder, and the Process class.
- Using the .exec() method of the Runtime class
- Using ProcessBuilder
- Command Line Arguments in Java
- Using the Process class
- Passing command-line arguments
- Running a process from a different directory
- Other helpful code examples for executing command line in Java
- Conclusion
- How to run a command line in Java?
- Can I run Java project command line?
- Which command is used to execute Java?
- How to do command line arguments in Java?
Java is a well-known programming language that can be used to create different types of applications, including command-line applications. When building such applications in Java, it is essential to know how to execute command line commands efficiently. There are different ways to execute command line in Java, and this blog post will explore the best way to do so, along with helpful tips and best practices.
Using the .exec() method of the Runtime class
The .exec() method is a straightforward way to execute command line commands in Java. This method can be used to execute a command in a new process. The command can be passed as a string argument to the method. The I/O for a program run by .exec() is always pipes from and to the Java process. Properly handling input, output, and error streams is essential when using this method.
Here’s an example of using the .exec() method to run a simple command:
public static void main(String[] args) throws IOException < Process process = Runtime.getRuntime().exec("ls -l"); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) < System.out.println(line); >reader.close(); >
This code runs the ls -l command in a new process and prints the output to the console. The BufferedReader class is used to read the output of the command.
Using ProcessBuilder
ProcessBuilder is another way to execute command line commands in Java. This class allows for more control over the process being run than .exec() . The command can be passed as a list of strings to the constructor of the ProcessBuilder class. ProcessBuilder can be used to set environment variables, working directory, and redirect input and output streams. Properly closing streams after use is important when using this method.
Here’s an example of using ProcessBuilder to run a command:
public static void main(String[] args) throws IOException < ProcessBuilder processBuilder = new ProcessBuilder(); processBuilder.command("ls", "-l"); Process process = processBuilder.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) < System.out.println(line); >reader.close(); >
This code runs the same ls -l command as before, but using ProcessBuilder instead of .exec() . The command() method is used to set the command to be run.
Command Line Arguments in Java
Using the Process class
The Process class can be used to execute complex process command lines in Java. The exit value of the process being run can be obtained using the exitValue() method of the Process class. The input, output, and error streams of the process being run can be controlled using the methods of the Process class. Properly handling input, output, and error streams is important when using this method.
Here’s an example of using the Process class to run a command:
public static void main(String[] args) throws IOException, InterruptedException < ProcessBuilder processBuilder = new ProcessBuilder(); processBuilder.command("ping", "google.com"); Process process = processBuilder.start(); process.waitFor(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) < System.out.println(line); >reader.close(); >
This code runs the ping google.com command and waits for it to complete before reading the output. The waitFor() method is used to wait for the process to complete.
Passing command-line arguments
Command-line arguments can be passed through the main method of a Java application using the JVM. A JAR application can accept any number of arguments, including zero arguments. Properly handling command-line arguments is important to ensure the correct execution of the program.
Here’s an example of using command-line arguments in a Java application:
public static void main(String[] args) throws IOException < if (args.length == 0) < System.out.println("No arguments provided"); System.exit(1); >ProcessBuilder processBuilder = new ProcessBuilder(); processBuilder.command("echo", args[0]); Process process = processBuilder.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) < System.out.println(line); >reader.close(); >
This code takes the first command-line argument and uses it as an argument to the echo command.
Running a process from a different directory
To run a process from a different directory than the working directory of the Java program, change directory and then run the process. The working directory can be obtained using the System.getProperty(«user.dir») method. Properly setting the working directory is important to ensure the correct execution of the program.
Here’s an example of running a process from a different directory:
public static void main(String[] args) throws IOException < String workingDir = System.getProperty("user.dir"); ProcessBuilder processBuilder = new ProcessBuilder(); processBuilder.command("ls", "-l"); processBuilder.directory(new File(workingDir + "/src")); Process process = processBuilder.start(); BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream())); String line; while ((line = reader.readLine()) != null) < System.out.println(line); >reader.close(); >
This code runs the ls -l command from the src directory of the working directory.
Other helpful code examples for executing command line in Java
In Java case in point, cmd java compile code example
javac MyFisrtProgam.java // enter to compile java MyfirstProgram // run program
In Java case in point, java run cmd code sample
public void excCommand(String new_dir)< Runtime rt = Runtime.getRuntime(); try < rt.exec(new String[]); > catch (IOException e) < // TODO Auto-generated catch block e.printStackTrace(); >>
// Assuming that you have an executable jar java -jar myJavaProject.jar// Assuming that you have packaged jar java -jar target/myJavaProject.jar
import java.io.*;public class CmdTest < public static void main(String[] args) throws Exception < ProcessBuilder builder = new ProcessBuilder( "cmd.exe", "/c", "cd \"C:\\Program Files\\Microsoft SQL Server\" && dir"); builder.redirectErrorStream(true); Process p = builder.start(); BufferedReader r = new BufferedReader(new InputStreamReader(p.getInputStream())); String line; while (true) < line = r.readLine(); if (line == null) < break; >System.out.println(line); > > >
In Kotlin , java run cmd command code sample
fun excCommand(cmd: String) < val rt = Runtime.getRuntime() try < rt.exec(arrayOf("cmd.exe", "/c", cmd)) >catch (e: IOException) < // TODO Auto-generated catch block e.printStackTrace() >>
In Java , in particular, run java application in commande line code sample
java -jar target/spring-cloud-gateway-keycloak-oauth2-0.0.1-SNAPSHOT.jarjava -jar target/product-service-0.0.1-SNAPSHOT.jar
Conclusion
When it comes to executing command line in Java, there are different ways to do it. This blog post has explored the best practices and tips for using the .exec() method of the Runtime class, ProcessBuilder, and the Process class. It has also covered how to pass command-line arguments and run a process from a different directory. Properly handling input, output, and error streams, command-line arguments, and setting the working directory is essential to ensure the correct execution of the program.