Java Runtime.exec()

In this guide, you will learn about the Runtime.exec() method in Java programming and how to use it with an example.

1. Runtime.exec() Method Overview

Definition:

In Java, the Runtime.exec() method is used to execute external commands, applications, scripts, or processes from a Java application. 

This method belongs to the Runtime class, which is part of java.lang package. 

The Runtime.exec() method creates a native process representing the command or application and returns a Process object representing the newly created process.

Syntax:

1. public Process exec(String command) throws IOException
2. public Process exec(String[] cmdarray) throws IOException
3. public Process exec(String command, String[] envp) throws IOException
4. public Process exec(String[] cmdarray, String[] envp) throws IOException
5. public Process exec(String command, String[] envp, File dir) throws IOException
6. public Process exec(String[] cmdarray, String[] envp, File dir) throws IOException

Parameters:

- command: A specified system command.

- cmdarray: An array containing the command to call and its arguments.

- envp: An array of strings, each element of which has environment variable settings in the format name=value, or null if the subprocess should inherit the environment of the current process.

- dir: The directory from which the command is to be run, or null if the subprocess should inherit the working directory of the current process.

Key Points:

- This method returns a Process object for managing the subprocess.

- You can retrieve the output stream, input stream, and error stream of the subprocess using the Process object.

- Ensure you handle the streams properly to prevent deadlocks.

- The subprocess is not synchronized with the Java application, so you might want to use methods like waitFor() on the Process object to have your Java program wait for the subprocess to finish.

- Be cautious while executing arbitrary commands, especially if they are derived from untrusted sources.

2. Runtime.exec() Method Example

public class ExecuteCommandExample {
    public static void main(String[] args) {
        Runtime runtime = Runtime.getRuntime();

        try {
            // Using the first syntax: exec(String command)
            Process process = runtime.exec("ping -c 1 www.google.com");

            // Retrieving the input stream (where the command sends its output)
            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }

            // Wait for the process to exit and get the return value
            int exitValue = process.waitFor();
            System.out.println("Process exit value: " + exitValue);

        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }
}

Output:

PING www.google.com (172.217.5.110): 56 data bytes
64 bytes from 172.217.5.110: icmp_seq=0 ttl=117 time=11.632 ms
--- www.google.com ping statistics ---
1 packets transmitted, 1 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 11.632/11.632/11.632/0.000 ms
Process exit value: 0
(Note: The output values are hypothetical and may differ based on the network conditions and the specific IP address returned for www.google.com.)

Explanation:

In the provided example, we used the Runtime.exec() method to execute the ping command for www.google.com. 

We then retrieved the output of the command using the input stream of the Process object. 

After processing all the output, we used the waitFor() method to ensure our program waited until the subprocess (ping command) completed its execution. 

The exit value of the process provides an indication of success (typically 0) or failure (non-zero).

Comments