Executing Shell command from Java code

In this post let us learn the way of executing a shell command through a java class.
In JAVA we have a class called “java.lang.Runtime” which is used to interact with Runtime system and has facility to execute any shell commands using Runtime.getRuntime().exec() method.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
class ExecuteProcess {
public void executeCommand() {
String command = "ls -ltr";
Runtime run = Runtime.getRuntime();
Process process = null;
try {
process = run.exec(command);
}
catch (IOException e) {
e.printStackTrace();
}
try {
process.waitFor();
} catch (InterruptedException e) {
e.printStackTrace();
}
BufferedReader br = new BufferedReader(new InputStreamReader(
process.getInputStream()));
String line = "";
try {
while ((line = br.readLine()) != null) {
System.out.println(line);
}
}
catch (IOException e) {
e.printStackTrace();
}
}
}
Note: This kind of implementations are discourage by java programming language since you will lose platform independence which is why we mostly used JAVA.
Reference



