Home  >  Article  >  Java  >  How Can I Execute System Commands in Java?

How Can I Execute System Commands in Java?

Barbara Streisand
Barbara StreisandOriginal
2024-11-02 17:57:02224browse

How Can I Execute System Commands in Java?

Executing System Commands in Java

This article discusses executing system commands in Java using the Runtime.exec() method. The method allows you to launch a separate process and interact with its standard input, output, and error streams.

To demonstrate its usage, consider the following code:

<code class="java">public class ImprovedCommandExecution {

    public static void main(String[] args) {
        try {
            Runtime r = Runtime.getRuntime();
            Process p = r.exec("uname -a");
            p.waitFor();
            BufferedReader b = new BufferedReader(new InputStreamReader(p.getInputStream()));

            StringBuilder output = new StringBuilder();
            String line;
            while ((line = b.readLine()) != null) {
                output.append(line).append("\n");
            }

            b.close();

            System.out.println(output);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}</code>

In this example, we:

  1. Get a reference to the Runtime object, which allows us to execute system commands.
  2. Use exec() to start a process that executes the "uname -a" command.
  3. Wait for the process to finish using waitFor().
  4. Obtain the process's input stream and use a BufferedReader to read its output.
  5. Append each line of output to a StringBuilder and print the final output.

This code stores the output from the system command in a String, making it easy to use within your Java program.

The above is the detailed content of How Can I Execute System Commands in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn