- How to run linux commands in java?
- Method 1: Using Java ProcessBuilder Class
- Method 2: Using Runtime.getRuntime().exec() Method
- Method 3: Using JSch Library
- 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 run linux commands in java?
To run Linux commands in a Java program, there are several methods available. Each method has its own advantages and disadvantages, depending on the specific requirements of the task at hand. In this article, we will discuss the most commonly used methods for running Linux commands in Java. The methods listed here are intended for developers who have some experience with Java and Linux, and are looking for ways to automate tasks or interact with the operating system from within their Java programs.
Method 1: Using Java ProcessBuilder Class
To run Linux commands in Java using the ProcessBuilder class, follow these steps:
- Create a ProcessBuilder object and set the command to be executed as argument to its constructor.
ProcessBuilder processBuilder = new ProcessBuilder("ls", "-l");
- Redirect the standard output and error streams of the command to the Java process by calling the inheritIO() method of the ProcessBuilder object.
Process process = processBuilder.start();
int exitCode = process.waitFor();
Here is an example code that lists the files in the current directory using the ls command:
import java.io.IOException; public class LinuxCommandRunner public static void main(String[] args) throws IOException, InterruptedException ProcessBuilder processBuilder = new ProcessBuilder("ls", "-l"); processBuilder.inheritIO(); Process process = processBuilder.start(); int exitCode = process.waitFor(); System.out.println("Exited with error code " + exitCode); > >
You can also pass arguments to the command using the ProcessBuilder object. Here is an example code that creates a new directory using the mkdir command:
import java.io.IOException; public class LinuxCommandRunner public static void main(String[] args) throws IOException, InterruptedException ProcessBuilder processBuilder = new ProcessBuilder("mkdir", "newDirectory"); processBuilder.inheritIO(); Process process = processBuilder.start(); int exitCode = process.waitFor(); System.out.println("Exited with error code " + exitCode); > >
In this example, the mkdir command is executed with the argument newDirectory , which creates a new directory with that name.
Using the ProcessBuilder class, you can run any Linux command in your Java program and get the output and error streams of the command as if it was executed in the Linux terminal.
Method 2: Using Runtime.getRuntime().exec() Method
To run Linux commands in Java using the Runtime.getRuntime().exec() method, follow these steps:
- Create a Process object by calling the exec() method of the Runtime class, passing the command you want to execute as a string parameter.
Process process = Runtime.getRuntime().exec("ls -la");
- Use the getInputStream() method of the Process object to get the output of the command as an input stream.
InputStream inputStream = process.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream));
- Use the readLine() method of the BufferedReader object to read the output of the command line by line.
String line; while ((line = reader.readLine()) != null)
int exitCode = process.waitFor();
Here’s an example that lists the files in the current directory:
import java.io.BufferedReader; import java.io.InputStream; import java.io.InputStreamReader; public class LinuxCommandRunner public static void main(String[] args) throws Exception Process process = Runtime.getRuntime().exec("ls -la"); InputStream inputStream = process.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) System.out.println(line); > int exitCode = process.waitFor(); System.out.println("Exited with error code " + exitCode); > >
This code will execute the ls -la command and print the output to the console. You can replace this command with any other Linux command you want to run.
Method 3: Using JSch Library
To run Linux commands in Java, we can use the JSch library. Here’s a step-by-step guide on how to do it:
- First, we need to add the JSch library to our project. We can do this by adding the following dependency to our pom.xml file:
dependency> groupId>com.jcraftgroupId> artifactId>jschartifactId> version>0.1.55version> dependency>
- Next, we need to create a session with the remote Linux server. We can do this by calling the getSession method on the JSch instance and passing in the username, hostname, and port number:
Session session = jsch.getSession("username", "hostname", 22);
session.setPassword("password");
Channel channel = session.openChannel("shell"); channel.connect();
- We can then send commands to the remote server by writing to the output stream of the Channel :
OutputStream outputStream = channel.getOutputStream(); outputStream.write("ls -l\n".getBytes()); outputStream.flush();
- To read the output of the command, we can create a BufferedReader and read from the input stream of the Channel :
InputStream inputStream = channel.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) System.out.println(line); >
channel.disconnect(); session.disconnect();
JSch jsch = new JSch(); Session session = jsch.getSession("username", "hostname", 22); session.setPassword("password"); session.connect(); Channel channel = session.openChannel("shell"); channel.connect(); OutputStream outputStream = channel.getOutputStream(); outputStream.write("ls -l\n".getBytes()); outputStream.flush(); InputStream inputStream = channel.getInputStream(); BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream)); String line; while ((line = reader.readLine()) != null) System.out.println(line); > channel.disconnect(); session.disconnect();
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.