ProcessBuilder class in Java

The ProcessBuilder class provides methods for creating and configuring operating system processes.

Each ProcessBuilder instance manages a collection of process attributes.
The start method creates a new Process instance with those attributes. The start method can be invoked repeatedly from the same instance to create new subprocesses with identical or related attributes.

Constructors and APIs

ProcessBuilder class in Java

package com.java.core;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Map;

public class ProcessBuilderExample {

    public static void main(String[] args) throws IOException, InterruptedException {

        executeCommand("ls");
        executeCommand("ps"); 

        Map < String, String > envMap = new ProcessBuilder().environment();
        envMap.entrySet().stream().forEach(e - > System.out.println(e.getKey() + " = " + e.getValue()));

    }

    public static void executeCommand(String command) throws IOException, InterruptedException {
        System.out.println("Executing command:" + command);
        ProcessBuilder processBuilder = new ProcessBuilder();
        Process process = processBuilder.command(command).start();
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));

        String line;
        while ((line = reader.readLine()) != null) {
            System.out.println(line);
        }
        process.waitFor();

    }

}
Executing command:ls
bin
src
Executing command:ps
PID TTY TIME CMD

***** ***** ***** *****

PATH = *****
SHELL = *****
USER = *****
TMPDIR = *****
....
HOME = *****

Leave a Reply

Your email address will not be published. Required fields are marked *