Skip to content
Related Articles

Related Articles

Improve Article
How to Execute Native Shell Commands from Java Program?
  • Last Updated : 03 Mar, 2021

A shell command is a command that we can trigger using a keyboard and a command-line or a shell instead of a Graphical user interface. Usually, we would trigger shell commands manually. However, there can be instances where this needs to be done programmatically through Java.

Java provides support to run native shell commands with two classes: RunTime and ProcessBuilder. The main disadvantage of using these classes and running shell commands from inside a Java Program is Java loses its portability.

What does losing portability mean?

Java goes by the principle “compile once, run anywhere.” This means that a Java program written and compiled on one operating system can run on any other operating system without making any changes. 

When we use either the ProcessBuilder or the Runtime classes to run Native shell commands, we make the Java program dependent on the underlying operating system. For example, a Java program running specifically Linux shell commands cannot run as-is on a Windows machine mainly because Windows has a different folder structure and shell commands.



Examples:

The first three examples will look at implementing the ProcessBuilder class to run shell commands in Java. The following example is for the RunTime class.

Example 1: Loss of portability.

This example shows what happens if we execute a Java program meant for the Linux/Unix operating system on a Windows operating system.  

Java




// if we execute a Java program meant for the Linux/Unix
// operating system on a Windows operating system
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
  
public class ShellCommandRunner4 {
    public static void main(String[] args)
    {
        try {
  
            System.out.println(
                System.getProperty("os.name"));
            System.out.println();
  
            // This process cannot be run on Windows. So the
            // program will throw an exception.
            ProcessBuilder pb
                = new ProcessBuilder("sh", "-c", "ls");
            // Exception thrown here because folder
            // structure of Windows and Linux are different.
            pb.directory(
                new File(System.getProperty("user.home")));
            // It will throw and exception
            Process process = pb.start();
  
            StringBuilder output = new StringBuilder();
            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(
                    "**************************** The Output is ******************************");
                System.out.println(output);
                System.exit(0);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

The output of the above program when run on a Windows machine.

Example 2: Run a simple shell command

This example shows how to run a simple Windows shell command. We use a list to build commands and then execute them using the “start” method of the ProcessBuilder class. The program runs the command to find the chrome browser processes from the tasklist running in the machine.

Java






// Run a simple Windows shell command
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.List;
  
public class ShellCommandRunner {
  
    public static void main(String[] args)
    {
  
        ProcessBuilder processBuilder
            = new ProcessBuilder();
  
        List<String> builderList = new ArrayList<>();
  
        // add the list of commands to a list
        builderList.add("cmd.exe");
        builderList.add("/C");
        builderList.add("tasklist | findstr chrome");
  
        try {
            // Using the list , trigger the command
            processBuilder.command(builderList);
            Process process = processBuilder.start();
  
            // To read the output list
            BufferedReader reader
                = new BufferedReader(new InputStreamReader(
                    process.getInputStream()));
  
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
  
            int exitCode = process.waitFor();
            System.out.println("\nExited with error code : "
                               + exitCode);
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Chrome browser processes.

Example 3: Run a bat file

This example shows how to run a simple .bat program in the Java console. The .bat file displays the windows system information. 

Java




// Run a simple .bat program in the Java console
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
  
public class ShellCommandRunner3 {
    public static void main(String[] args)
    {
        try {
            // File location for the bat script
            File dir = new File("D:\\bat_scripts");
            // Command to run the bat file in the same
            // console
            ProcessBuilder pb = new ProcessBuilder(
                "cmd.exe", "/C", "sysinfo.bat");
            pb.directory(dir);
            Process process = pb.start();
  
            StringBuilder output = new StringBuilder();
            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(
                    "**************************** The Output is ******************************");
                System.out.println(output);
                System.exit(0);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

System info bat file program output

Example 4:Run a shell command using the RunTime class.

This example shows how to run a simple command using the RunTime class. We use the exec() method of the Runtime class.

Java




// Run a simple command using the RunTime class
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
  
public class ShellCommandRunner2 {
  
    public static void main(String[] args)
    {
  
        try {
            Process process
                = Runtime.getRuntime().exec("where java");
  
            StringBuilder output = new StringBuilder();
  
            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(
                    "**************************** The Output is ******************************");
                System.out.println(output);
                System.exit(0);
            }
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

where java in Java program

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

My Personal Notes arrow_drop_up
Recommended Articles
Page :