📜  Java 9 Process API(1)

📅  最后修改于: 2023-12-03 15:01:28.279000             🧑  作者: Mango

Java 9 Process API

Java 9 introduces a new and improved Process API that provides more control over operating system processes. This API makes it easier to perform common tasks such as managing processes, capturing process output, and controlling process shutdown.

Creating a Process

To create a new process in Java 9, you can use the new ProcessBuilder class. This class provides several methods for setting up the process, such as setting the command to execute and the working directory. Once the ProcessBuilder is set up, you can start the process using the start() method.

Here's an example that starts a new process to execute the ls command:

ProcessBuilder processBuilder = new ProcessBuilder("ls", "-l", "/tmp");

try {
    Process process = processBuilder.start();
} catch (IOException e) {
    // Handle exception
}
Capturing Process Output

You can capture the output of a process using the new Process.getInputStream() and Process.getErrorStream() methods. These methods return an input stream that you can read from to retrieve the process output.

Here's an example that captures and prints the output of a process:

ProcessBuilder processBuilder = new ProcessBuilder("ls", "-l", "/tmp");

try {
    Process process = processBuilder.start();

    BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line;

    while ((line = reader.readLine()) != null) {
        System.out.println(line);
    }
} catch (IOException e) {
    // Handle exception
}
Controlling Process Shutdown

The new Process class provides several methods for controlling the process, such as sending input to the process and waiting for the process to complete. One important method is Process.destroy(), which stops the process.

Here's an example that starts a new process and waits for it to complete, or destroys the process after a timeout:

ProcessBuilder processBuilder = new ProcessBuilder("ls", "-l", "/tmp");

try {
    Process process = processBuilder.start();

    // Wait for process to complete
    boolean completed = process.waitFor(1, TimeUnit.SECONDS);

    if (!completed) {
        // Process running for more than 1 second, destroy it
        process.destroy();
    }
} catch (IOException | InterruptedException e) {
    // Handle exception
}
Conclusion

The new Process API in Java 9 provides powerful new features for managing operating system processes. With this API, you can easily create and control processes, capture process output, and more.