Execute the shell commands using ProcessBuilder in Java

Contents

We can execute the shell commands using the Java.lang.ProcessBuilder class in Java.Lets see the program to execute the shell commands.

Java Program to execute the shell commands:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class RunShellCommand{

	public static void main(String[] args) throws IOException, InterruptedException {
		String cmd = "ls -ltr";
	    
	    ProcessBuilder builder = new ProcessBuilder();
		builder.command("sh","-c",cmd);
    
        Process result = builder.start();
        
        int exitcode=result.waitFor(); 
        if (exitcode == 0) {
			System.out.println("Success!");
		} else {
			System.out.println("Abnormal failure");
			System.out.println("Quitting the program");
			System.exit(1);
		}
        System.out.println("Exit code: " + exitcode);
        
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(result.getInputStream())); 
        String output; 
        while ((output = stdInput.readLine()) != null) 
        { 
            System.out.println(output); 
        }        
	}
}

Java Program to execute command prompt commands

If you want to run the command prompt commands,you can use the cmd.exe instead of sh in the builder command list.It helps java to identify the environment to run the given commands.

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class RunCmdPrompt{

	public static void main(String[] args) throws IOException, InterruptedException {
		String cmd = "dir";
	    
	    ProcessBuilder builder = new ProcessBuilder();
		builder.command("cmd.exe","/c",cmd);
    
        Process result = builder.start();
        
        int exitcode=result.waitFor(); 
        System.out.println("Exit code: " + exitcode);
        if (exitcode == 0) {
			System.out.println("Success!");
		} else {
			System.out.println("Abnormal failure");
			System.out.println("Quitting the program");
			System.exit(1);
		}
        
        BufferedReader stdInput = new BufferedReader(new InputStreamReader(result.getInputStream())); 
        String output; 
        while ((output = stdInput.readLine()) != null) 
        { 
            System.out.println(output); 
        }        
	}
}

Output:

Exit code: 0
Success!

 Directory of C:\Users\revisit\workspace\Testpgm

03/20/2019  11:34 AM    <DIR>          .
03/20/2019  11:34 AM    <DIR>          ..
03/20/2019  11:34 AM    <DIR>          .settings
03/26/2019  10:51 PM    <DIR>          bin
03/26/2019  10:51 PM    <DIR>          src
               2 File(s)            686 bytes
               5 Dir(s)  336,018,677,760 bytes free