Guide to java.lang.ProcessBuilder API – java.lang.ProcessBuilder API指南

最后修改: 2019年 3月 13日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

The Process API provides a powerful way to execute operating system commands in Java. However, it has several options that can make it cumbersome to work with.

Process API提供了一种在Java中执行操作系统命令的强大方式。然而,它有几个选项可能会使它的工作变得很麻烦。

In this tutorial, we’ll take a look at how Java alleviates that with the ProcessBuilder API.

在本教程中,我们将看看Java如何通过ProcessBuilder API来缓解这一问题。

2. ProcessBuilder API

2.ProcessBuilder API

The ProcessBuilder class provides methods for creating and configuring operating system processes. Each ProcessBuilder instance allows us to manage a collection of process attributes. We can then start a new Process with those given attributes.

ProcessBuilder类提供了创建和配置操作系统进程的方法。每个ProcessBuilder实例允许我们管理一个进程属性的集合。然后我们可以用这些给定的属性启动一个新的Process

Here are a few common scenarios where we could use this API:

以下是我们可以使用这个API的几个常见场景。

  • Find the current Java version
  • Set-up a custom key-value map for our environment
  • Change the working directory of where our shell command is running
  • Redirect input and output streams to custom replacements
  • Inherit both of the streams of the current JVM process
  • Execute a shell command from Java code

We’ll take a look at practical examples for each of these in later sections.

我们将在后面的章节中看一下每个人的实际例子。

But before we dive into the working code, let’s take a look at what kind of functionality this API provides.

但在我们深入研究工作代码之前,让我们看看这个API提供了什么样的功能。

2.1. Method Summary

2.1.方法概述

In this section, we’re going to take a step back and briefly look at the most important methods in the ProcessBuilder class. This will help us when we dive into some real examples later on:

在本节中,我们将退后一步,简要地看一下ProcessBuilder类中最重要的方法。这将有助于我们在以后深入研究一些真正的例子。

  • ProcessBuilder(String... command)

    To create a new process builder with the specified operating system program and arguments, we can use this convenient constructor.

    要用指定的操作系统程序和参数创建一个新的进程构建器,我们可以使用这个方便的构造函数。

  • directory(File directory)

    We can override the default working directory of the current process by calling the directory method and passing a File object. By default, the current working directory is set to the value returned by the user.dir system property.

    我们可以通过调用directory方法并传递一个File对象来重写当前进程的默认工作目录。默认情况下,当前工作目录被设置为由user.dir系统属性返回的值

  • environment()

    If we want to get the current environment variables, we can simply call the environment method. It returns us a copy of the current process environment using System.getenv() but as a Map.

    如果我们想获得当前的环境变量,我们可以简单地调用environment方法。它使用System.getenv()但作为Map返回我们当前进程环境的一个副本。

  • inheritIO()

    If we want to specify that the source and destination for our subprocess standard I/O should be the same as that of the current Java process, we can use the inheritIO method.

    如果我们想指定子进程的标准I/O的源和目的应该与当前Java进程的相同,我们可以使用inheritIO方法。

  • redirectInput(File file), redirectOutput(File file), redirectError(File file)

    When we want to redirect the process builder’s standard input, output and error destination to a file, we have these three similar redirect methods at our disposal.

    当我们想把进程建立者的标准输入、输出和错误目的地重定向到一个文件时,我们有这三种类似的重定向方法可以使用。

  • start()

    Last but not least, to start a new process with what we’ve configured, we simply call start().

    最后但并非最不重要的是,要用我们所配置的东西启动一个新的进程,我们只需调用start()

We should note that this class is NOT synchronized. For example, if we have multiple threads accessing a ProcessBuilder instance concurrently then the synchronization must be managed externally.

我们应该注意,这个类是不同步的。例如,如果我们有多个线程同时访问一个ProcessBuilder实例,那么同步必须由外部管理。

3. Examples

3.例子

Now that we have a basic understanding of the ProcessBuilder API, let’s step through some examples.

现在我们对ProcessBuilder API有了基本的了解,让我们来看看一些例子。

3.1. Using ProcessBuilder to Print the Version of Java

3.1.使用ProcessBuilder来打印Java的版本

In this first example, we’ll run the java command with one argument in order to get the version.

在这第一个例子中,我们将运行带有一个参数的java命令,以便获得版本

Process process = new ProcessBuilder("java", "-version").start();

First, we create our ProcessBuilder object passing the command and argument values to the constructor. Next, we start the process using the start() method to get a Process object.

首先,我们创建ProcessBuilder对象,将命令和参数值传递给构造函数。接下来,我们使用start()方法启动进程,得到一个Process对象。

Now let’s see how to handle the output:

现在我们来看看如何处理输出。

List<String> results = readOutput(process.getInputStream());

assertThat("Results should not be empty", results, is(not(empty())));
assertThat("Results should contain java version: ", results, hasItem(containsString("java version")));

int exitCode = process.waitFor();
assertEquals("No errors should be detected", 0, exitCode);

Here we’re reading the process output and verifying the contents is that we expect. In the final step, we wait for the process to finish using process.waitFor().

在这里,我们正在读取进程的输出,并验证其内容是我们所期望的。在最后一步,我们使用process.waitFor()等待进程结束。

Once the process has finished, the return value tells us whether the process was successful or not.

一旦进程结束,返回值告诉我们进程是否成功

A few important points to keep in mind:

有几个重要的点需要记住。

  • The arguments must be in the right order
  • Moreover, in this example, the default working directory and environment are used
  • We deliberately don’t call process.waitFor() until after we’ve read the output because the output buffer might stall the process
  • We’ve made the assumption that the java command is available via the PATH variable

3.2. Starting a Process With a Modified Environment

3.2.用修改过的环境启动一个进程

In this next example, we’re going to see how to modify the working environment.

在接下来的例子中,我们将看到如何修改工作环境。

But before we do that let’s begin by taking a look at the kind of information we can find in the default environment:

但在这之前,让我们先看看我们能在默认环境中找到什么样的信息

ProcessBuilder processBuilder = new ProcessBuilder();        
Map<String, String> environment = processBuilder.environment();
environment.forEach((key, value) -> System.out.println(key + value));

This simply prints out each of the variable entries which are provided by default:

这只是打印出默认提供的每个变量条目。

PATH/usr/bin:/bin:/usr/sbin:/sbin
SHELL/bin/bash
...

Now we’re going to add a new environment variable to our ProcessBuilder object and run a command to output its value:

现在我们要为我们的ProcessBuilder对象添加一个新的环境变量,并运行一个命令来输出其值:

environment.put("GREETING", "Hola Mundo");

processBuilder.command("/bin/bash", "-c", "echo $GREETING");
Process process = processBuilder.start();

Let’s decompose the steps to understand what we’ve done:

让我们分解一下步骤,以了解我们做了什么。

  • Add a variable called ‘GREETING’ with a value of ‘Hola Mundo’ to our environment which is a standard Map<String, String>
  • This time, rather than using the constructor we set the command and arguments via the command(String… command) method directly.
  • We then start our process as per the previous example.

To complete the example, we verify the output contains our greeting:

为了完成这个例子,我们验证输出包含我们的问候语。

List<String> results = readOutput(process.getInputStream());
assertThat("Results should not be empty", results, is(not(empty())));
assertThat("Results should contain java version: ", results, hasItem(containsString("Hola Mundo")));

3.3. Starting a Process With a Modified Working Directory

3.3.用修改过的工作目录启动进程

Sometimes it can be useful to change the working directory. In our next example we’re going to see how to do just that:

有时候,改变工作目录是很有用的。在我们的下一个例子中,我们将看到如何做到这一点。

@Test
public void givenProcessBuilder_whenModifyWorkingDir_thenSuccess() 
  throws IOException, InterruptedException {
    ProcessBuilder processBuilder = new ProcessBuilder("/bin/sh", "-c", "ls");

    processBuilder.directory(new File("src"));
    Process process = processBuilder.start();

    List<String> results = readOutput(process.getInputStream());
    assertThat("Results should not be empty", results, is(not(empty())));
    assertThat("Results should contain directory listing: ", results, contains("main", "test"));

    int exitCode = process.waitFor();
    assertEquals("No errors should be detected", 0, exitCode);
}

In the above example, we set the working directory to the project’s src dir using the convenience method directory(File directory). We then run a simple directory listing command and check that the output contains the subdirectories main and test.

在上面的例子中,我们使用方便的方法directory(File directory)将工作目录设置为项目的src目录。然后我们运行一个简单的目录列表命令,检查输出是否包含子目录maintest

3.4. Redirecting Standard Input and Output

3.4.重定向标准输入和输出

In the real world, we will probably want to capture the results of our running processes inside a log file for further analysis. Luckily the ProcessBuilder API has built-in support for exactly this as we will see in this example.

在现实世界中,我们可能希望在日志文件中捕获我们运行进程的结果,以便进一步分析。幸运的是,ProcessBuilder API有内置的支持,正如我们将在这个例子中看到的那样。

By default, our process reads input from a pipe. We can access this pipe via the output stream returned by Process.getOutputStream().

默认情况下,我们的进程从一个管道读取输入。我们可以通过Process.getOutputStream()返回的输出流访问这个管道。

However, as we’ll see shortly, the standard output may be redirected to another source such as a file using the method redirectOutput. In this case, getOutputStream() will return a ProcessBuilder.NullOutputStream.

然而,我们很快就会看到,标准输出可以通过redirectOutput方法被重定向到另一个来源,比如一个文件。在这种情况下,getOutputStream()将返回ProcessBuilder.NullOutputStream

Let’s return to our original example to print out the version of Java. But this time let’s redirect the output to a log file instead of the standard output pipe:

让我们回到原来的例子,打印出Java的版本。但这次我们把输出重定向到一个日志文件,而不是标准输出管道。

ProcessBuilder processBuilder = new ProcessBuilder("java", "-version");

processBuilder.redirectErrorStream(true);
File log = folder.newFile("java-version.log");
processBuilder.redirectOutput(log);

Process process = processBuilder.start();

In the above example, we create a new temporary file called log and tell our ProcessBuilder to redirect output to this file destination.

在上面的例子中,我们创建了一个名为log的新临时文件,并告诉我们的ProcessBuilder将输出重定向到这个文件目的地

In this last snippet, we simply check that getInputStream() is indeed null and that the contents of our file are as expected:

在这最后一个片段中,我们简单地检查getInputStream()是否确实为null,以及我们文件的内容是否符合预期。

assertEquals("If redirected, should be -1 ", -1, process.getInputStream().read());
List<String> lines = Files.lines(log.toPath()).collect(Collectors.toList());
assertThat("Results should contain java version: ", lines, hasItem(containsString("java version")));

Now let’s take a look at a slight variation on this example. For example when we wish to append to a log file rather than create a new one each time:

现在让我们来看看这个例子的一个小变化。例如,当我们希望追加到一个日志文件,而不是每次都创建一个新文件时

File log = tempFolder.newFile("java-version-append.log");
processBuilder.redirectErrorStream(true);
processBuilder.redirectOutput(Redirect.appendTo(log));

It’s also important to mention the call to redirectErrorStream(true). In case of any errors, the error output will be merged into the normal process output file.

同样重要的是要提到对redirectErrorStream(true)的调用。如果出现任何错误,错误输出将被合并到正常的进程输出文件中。

We can, of course, specify individual files for the standard output and the standard error output:

当然,我们也可以为标准输出和标准错误输出指定单独的文件。

File outputLog = tempFolder.newFile("standard-output.log");
File errorLog = tempFolder.newFile("error.log");

processBuilder.redirectOutput(Redirect.appendTo(outputLog));
processBuilder.redirectError(Redirect.appendTo(errorLog));

3.5. Inheriting the I/O of the Current Process

3.5.继承当前进程的I/O

In this penultimate example, we’ll see the inheritIO() method in action. We can use this method when we want to redirect the sub-process I/O to the standard I/O of the current process:

在这个倒数第二个例子中,我们将看到inheritIO()方法的作用。当我们想把子进程的I/O重定向到当前进程的标准I/O时,我们可以使用这个方法:

@Test
public void givenProcessBuilder_whenInheritIO_thenSuccess() throws IOException, InterruptedException {
    ProcessBuilder processBuilder = new ProcessBuilder("/bin/sh", "-c", "echo hello");

    processBuilder.inheritIO();
    Process process = processBuilder.start();

    int exitCode = process.waitFor();
    assertEquals("No errors should be detected", 0, exitCode);
}

In the above example, by using the inheritIO() method we see the output of a simple command in the console in our IDE.

在上面的例子中,通过使用inheritIO()方法,我们在IDE的控制台中看到一个简单命令的输出。

In the next section, we’re going to take a look at what additions were made to the ProcessBuilder API in Java 9.

在下一节中,我们将看看Java 9中对ProcessBuilder API做了哪些补充。

4. Java 9 Additions

4.Java 9的补充

Java 9 introduced the concept of pipelines to the ProcessBuilder API:

Java 9为ProcessBuilder API引入了管道的概念:

public static List<Process> startPipeline​(List<ProcessBuilder> builders)

Using the startPipeline method we can pass a list of ProcessBuilder objects. This static method will then start a Process for each ProcessBuilder. Thus, creating a pipeline of processes which are linked by their standard output and standard input streams.

使用startPipeline方法,我们可以传递一个ProcessBuilder对象的列表。然后这个静态方法将为每个ProcessBuilder启动一个Process。因此,创建一个由标准输出和标准输入流连接的进程流水线。

For example, if we want to run something like this:

例如,如果我们想运行这样的东西。

find . -name *.java -type f | wc -l

What we’d do is create a process builder for each isolated command and compose them into a pipeline:

我们要做的是为每个孤立的命令创建一个流程生成器,并将它们组成一个管道。

@Test
public void givenProcessBuilder_whenStartingPipeline_thenSuccess()
  throws IOException, InterruptedException {
    List builders = Arrays.asList(
      new ProcessBuilder("find", "src", "-name", "*.java", "-type", "f"), 
      new ProcessBuilder("wc", "-l"));

    List processes = ProcessBuilder.startPipeline(builders);
    Process last = processes.get(processes.size() - 1);

    List output = readOutput(last.getInputStream());
    assertThat("Results should not be empty", output, is(not(empty())));
}

In this example, we’re searching for all the java files inside the src directory and piping the results into another process to count them.

在这个例子中,我们正在搜索src目录中的所有java文件,并将结果输入另一个进程进行统计。

To learn about other improvements made to the Process API in Java 9, check out our great article on Java 9 Process API Improvements.

要了解 Java 9 中对 Process API 所做的其他改进,请查看我们关于Java 9 Process API 改进的精彩文章。

5. Conclusion

5.结论

To summarize, in this tutorial, we’ve explored the java.lang.ProcessBuilder API in detail.

总结一下,在本教程中,我们已经详细地探讨了java.lang.ProcessBuilder API。

First, we started by explaining what can be done with the API and summarized the most important methods.

首先,我们首先解释了用API可以做什么,并总结了最重要的方法。

Next, we took a look at a number of practical examples. Finally, we looked at what new additions were introduced to the API in Java 9.

接下来,我们看了一些实际的例子。最后,我们看了一下在Java 9中为API引入了哪些新的内容。

As always, the full source code of the article is available over on GitHub.

一如既往,文章的完整源代码可在GitHub上获得