
In Java, you can execute external OS/shell commands.
There are two ways to start an operating system process/execute shell command within Java:
- java.lang.Runtime#exec(java.lang.String), since Java 1
- java.lang.ProcessBuilder, since Java 5
We will here show you both ways to execute Operating System/ Shell Commands
1. Using java.lang.Runtime
The java.lang.Runtime class allows the application to interface with the environment in which the application is running.
package com.jkoder.java.os;
import java.io.BufferedReader;
import java.io.InputStreamReader;
public class ExecuteOSShellComandRuntime {
public static void main(String[] args) {
StringBuffer commandOutput = new StringBuffer();
try {
Runtime rt = Runtime.getRuntime();
Process process = rt.exec("ls");
process.waitFor();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = reader.readLine()) != null) {
commandOutput.append(line + "\n");
}
System.out.println(commandOutput);
} catch (Exception e) {
e.printStackTrace();
}
}
}
Output of the above program
total 12 drwxrwxr-x 3 jkoder jkoder 4096 May 21 19:08 bin drwxrwxr-x 2 jkoder jkoder 4096 May 21 19:07 lib drwxrwxr-x 3 jkoder jkoder 4096 May 16 15:34 src
2. Using java.lang.ProcessBuilder
The java.lang.ProcessBuilder.command(String… command) method Sets this process builder’s operating system program and arguments. This is a convenience method that sets the command to a string list containing the same strings as the command array, in the same order. It is not checked whether command corresponds to a valid operating system command.
package com.jkoder.java.os;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Map;
public class ExecuteOSShellComandProcessBuilder {
public static void main(String[] args) throws java.io.IOException, java.lang.InterruptedException {
//Create ProcessBuilder instance
java.lang.ProcessBuilder processBuilder = new java.lang.ProcessBuilder("ls", "-l");
//Set environment variables
Map env = processBuilder.environment();
final Process process = processBuilder.start();
BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}
System.out.println("Program terminated!");
}
}
Output of the above program
total 12 drwxrwxr-x 3 jkoder jkoder 4096 May 21 19:08 bin drwxrwxr-x 2 jkoder jkoder 4096 May 21 19:07 lib drwxrwxr-x 3 jkoder jkoder 4096 May 16 15:34 src Program terminated!
Jkoder.com Tutorials, Tips and interview questions for Java, J2EE, Android, Spring, Hibernate, Javascript and other languages for software developers