Do you know Java: Execute Shell Commands


Two ways are shown here about how to execute shell scripts and commands with Java.

In this post I am showing two ways to execute shell scripts or shell commands from a Java app.

ProcessBuilder

ProcessBuilder class has been created to create and handle operating system processes.

ProcessBuilder#start method creates a single native process. Let us see how to do it.

ProcessBuilder builder = new ProcessBuilder();
builder.command("bash", "-c", "ping google.com");

Process process;
try {
    process = builder.start();
    System.out.println(process.pid());
    System.out.println(process.isAlive());
} catch (IOException e) {
    e.printStackTrace();
}

Runtime

Another way to run a command is to use Runtime#exec method.

Process process = Runtime.getRuntime().exec("ping google.com");
System.out.println(process.pid());
System.out.println(process.isAlive());

Output

Write the output of the command to the standard output

try (BufferedReader br = new BufferedReader(new InputStreamReader(process.getInputStream()))) {
    String line;
    while ((line = br.readLine()) != null) {
        System.out.println(line);
    }
}

We can use ProcessBuilder and Runtime#exec to execute shell scripts and commands.

You can find doc about ProcessBuilder
You can find doc about Runtime

Code can be found: https://github.com/torokmark/do-you-know-java