There are two ways to execute linux commands in java, we illustrated both of them below, google to know difference between these.
Below code is to print output of linux command to console using Runtime:import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public static void executelinuxcommand(String linux_command) {
StringBuilder output = new StringBuilder();
try {
Process process = Runtime.getRuntime().exec(linux_command);
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line;
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println("Linux command output :\n"+output.substring(0).toString());
} else {
System.out.println("***** Linux command failed to execute");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Below code is to print output of linux command to console using ProcessBuilder:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public static void executelinuxcommandprocessbuilder(String linuxcommand) {
ProcessBuilder processBuilder = new ProcessBuilder();
processBuilder.command(linuxcommand);
try {
Process process = processBuilder.start();
StringBuilder output = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String result;
while ((result = reader.readLine()) != null) {
output.append(result + "\n");
}
int exitVal = process.waitFor();
if (exitVal == 0) {
System.out.println("Linux command output :\n"+output.substring(0).toString());
} else {
System.out.println("**** Linux command failed to execute");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Comments
Post a Comment