You are currently viewing Java: How to Run System Commands and Capture Output

Java: How to Run System Commands and Capture Output

In Java programming, there may be times when you need to execute system commands from your application and capture their output. This could be useful for tasks such as running external programs, executing shell commands, or interacting with the operating system. In this blog post, we will explore how to run system commands and capture their output in Java.

Following code shows how to use the ProcessBuilder class to execute an external system command and capture the output. The code in this example runs the java –version command, which returns the version of Java currently installed on the running machine. It then prints the output of the command to the console.

This could be useful in a variety of scenarios, such as automating system tasks, executing batch processes, or integrating with other tools and applications, among other things:

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

public class Main {

    public static void main(String[] args) {

        ProcessBuilder builder = new ProcessBuilder();

        /* gets version of java installed on machine */
        builder.command("java", "--version");

        try {

            Process process = builder.start();

            try (BufferedReader reader = process.inputReader())
            {
                reader.lines().forEach(System.out::println);
            }

        } catch (IOException e) {
            System.out.println(e.getMessage());
        }

    }

}

I tend to keep all my codes simple and short. If you wish to see more, please subscribe to the newsletter. I hope you find this helpful.

Leave a Reply