Open In App

Java Runtime exec() Method with Examples

Last Updated : 23 Oct, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

The Runtime class’s exec() method is your key to making your Java application interact with the operating system, if you’ve ever wanted it to. In this post, we’ll examine the exec() method in great detail, dissect its fundamental ideas, and highlight all of its different applications.

Java Runtime exec() Method

Imagine you’re running a Java program, and you need to execute a system command. This could be anything from launching an external program to managing system processes. The exec() method is your gateway to this world of possibilities.

Here’s a simple way to think about it: You’re the conductor of a Java orchestra, and the exec() method is your baton. With it, you can instruct the OS to perform tasks outside the realm of Java, seamlessly integrating your application with the underlying system. So let’s get into the details.

Understanding the Core Concepts

Before we jump into the practical examples, let’s cover some essential concepts related to the exec() method:

  • Runtime Object: The exec() method belongs to the Runtime class, which represents the runtime environment of the application. You can obtain a Runtime object using the getRuntime() method.
  • Process: When you call exec(), it spawns a new native process. This process runs independently of your Java application and allows you to execute system commands.
  • ProcessBuilder: Under the hood, exec() uses a ProcessBuilder to start the native process. The ProcessBuilder class provides more control over the process configuration and is recommended for complex interactions.

Exploring different variants of exec() method

The exec() method has six variants, each tailored to different scenarios:

  • exec(String command) : This variant takes a single string command as input and executes it. For example, you can use it to open a text editor:

Runtime.getRuntime().exec(“notepad.exe”);

  • exec(String[] cmdarray) : Use this variant to execute a command and its arguments as separate strings in an array. Here’s how you can list files in a directory:

String[] cmd = {“ls”, “-l”, “/path/to/directory”};

Runtime.getRuntime().exec(cmd);

  • exec(String[] cmdarray, String[] envp) : In this version, you can also specify environment variables (envp) for the process. This is useful for customizing the execution environment.
  • exec(String[] cmdarray, String[] envp, File dir) : You can set the working directory for the process using this variant (dir). It’s handy when your command relies on relative paths.
  • exec(String command, String[] envp) : Here, you can pass the command as a single string and also provide environment variables. It’s a convenient way to execute a command with a customized environment.
  • exec(String command, String[] envp, File dir) : This is a combination of variants 1, 3, and 4. You can specify the command, environment variables, and the working directory.

Let’s Dive into Examples : Now, let’s get our hands dirty with some interactive examples:

Java




// Java program to demonstrate
// Java Runtime exec() method
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
  
//Driver class
public class GfgExecDemo {
  //main function
  public static void main(String[] args) {
        try {
            // Variant 1: exec(String command)
            // This variant executes the "notepad.exe" command, which opens Notepad.
            Process process1 = Runtime.getRuntime().exec("notepad.exe");
            int exitCode1 = process1.waitFor();
            System.out.println("Variant 1 - Exit Code: " + exitCode1);
  
            // Variant 2: exec(String[] cmdarray)
            // This variant executes the "ls -l /path/to/directory" command, listing files in a directory.
            String[] cmd2 = {"ls", "-l", "/path/to/directory"};
            Process process2 = Runtime.getRuntime().exec(cmd2);
            int exitCode2 = process2.waitFor();
            System.out.println("Variant 2 - Exit Code: " + exitCode2);
  
            // Variant 3: exec(String[] cmdarray, String[] envp)
            // This variant executes the "echo $HOME" command with a custom environment variable.
            String[] cmd3 = {"echo", "$HOME"};
            String[] env3 = {"HOME=/path/to/custom/home"};
            Process process3 = Runtime.getRuntime().exec(cmd3, env3);
            int exitCode3 = process3.waitFor();
            System.out.println("Variant 3 - Exit Code: " + exitCode3);
  
            // Variant 4: exec(String[] cmdarray, String[] envp, File dir)
            // This variant executes the "ls -l" command with a custom 
            // environment variable and working directory.
            String[] cmd4 = {"ls", "-l"};
            String[] env4 = {"HOME=/path/to/custom/home"};
            File workingDir4 = new File("/path/to/directory");
            Process process4 = Runtime.getRuntime().exec(cmd4, env4, workingDir4);
            int exitCode4 = process4.waitFor();
            System.out.println("Variant 4 - Exit Code: " + exitCode4);
  
            // Variant 5: exec(String command, String[] envp)
            // This variant executes the "echo $HOME" command with a custom environment variable.
            String cmd5 = "echo $HOME";
            String[] env5 = {"HOME=/path/to/custom/home"};
            Process process5 = Runtime.getRuntime().exec(cmd5, env5);
            int exitCode5 = process5.waitFor();
            System.out.println("Variant 5 - Exit Code: " + exitCode5);
  
            // Variant 6: exec(String command, String[] envp, File dir)
            // This variant executes the "ls -l" command with a custom environment 
            // variable and working directory.
            String cmd6 = "ls -l";
            String[] env6 = {"HOME=/path/to/custom/home"};
            File workingDir6 = new File("/path/to/directory");
            Process process6 = Runtime.getRuntime().exec(cmd6, env6, workingDir6);
            int exitCode6 = process6.waitFor();
            System.out.println("Variant 6 - Exit Code: " + exitCode6);
        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}


Output :

Variant 1 - Exit Code: 0
Variant 2 - Exit Code: 0
Variant 3 - Exit Code: 0
Variant 4 - Exit Code: 0
Variant 5 - Exit Code: 0
Variant 6 - Exit Code: 0

The exec() function in Java’s Runtime class provides various options for communicating with the operating system. Once you understand this, you can easily integrate system commands into your Java programs. Remember to choose the option that best suits your needs. You can then explore process execution possibilities with confidence.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads