Different ways to invoke shell commands in Java


Shell is a computer program that takes command from humans or from other programs and executes them. It can be a command line and graphical both. Mostly we use the command line to execute commands. On Linux, it is known as a Bash shell, and on windows known as cmd and power shell.

In many situations, while doing application development using Java we need to execute commands using the undelaying shell. For this Java provides class ProcessBuilder and Runtime.getRuntime().exec method.

ProcessBuilder class provides overloaded methods for setting commands, execution path, and error redirection methods.

Here are some examples of using the process builder class.

Ping Example using Windows powershell or cmd

public class PingCommandExample {
    public static void main(String[] args){
        ProcessBuilder  pb = new ProcessBuilder();
        // Ping 5 times, can use cmd or powershell both
        // pb.command("cmd.exe", "/c", "ping -n 5 google.com");
        pb.command("powershell", "/c", "ping -n 5 google.com");
        try {

            // Using processbuilder
            // Process process = pb.start();
            // Using Runtime.getRuntime().exec method
            Process process = Runtime.getRuntime().exec("powershell /c ping -n 5 google.com");
            BufferedReader reader =
                    new BufferedReader(new InputStreamReader(process.getInputStream()));

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            // wait to complete underlying command execution
            int exitCode = process.waitFor();
            System.out.println("\nTerminated with error code : " + exitCode);

        } catch (IOException ex) {
            ex.printStackTrace();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
}

Output

Pinging google.com [142.250.192.78] with 32 bytes of data:
Reply from 142.250.192.78: bytes=32 time=30ms TTL=119
Reply from 142.250.192.78: bytes=32 time=27ms TTL=119
Reply from 142.250.192.78: bytes=32 time=27ms TTL=119
Reply from 142.250.192.78: bytes=32 time=27ms TTL=119
Reply from 142.250.192.78: bytes=32 time=32ms TTL=119

Ping statistics for 142.250.192.78:
    Packets: Sent = 5, Received = 5, Lost = 0 (0% loss),
Approximate round trip times in milli-seconds:
    Minimum = 27ms, Maximum = 32ms, Average = 28ms

Terminated with error code : 0

In the same way, you can execute Linux and Unix commands.


Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.