Process process = new ProcessBuilder("java", "-version").start();
首先,我们创建
ProcessBuilder
对象,将命令和参数值传递给构造函数。接下来,我们使用
start()
方法启动进程来获取
一个 Process
对象。
现在让我们看看如何处理输出:
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);
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. 使用修改后的工作目录启动进程
有时更改工作目录可能很有用。在下一个示例中,我们将了解如何做到这一点:
@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);
}
在上面的例子中,我们使用方便的方法
目录(File directory)
将工作目录设置为项目的
src
dir。然后,我们运行一个简单的目录列表命令,并检查输出是否包含子目录
main
和
test
。
@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);
}
在上面的示例中,通过使用
inheritIO()
方法,我们在 IDE 的控制台中看到一个简单的命令的输出。
在下一节中,我们将看看Java 9中对
ProcessBuilder
API进行了哪些添加。
4. Java 9 新增内容
Java 9 在
ProcessBuilder
API 中引入了管道的概念:
public static List<Process> startPipeline(List<ProcessBuilder> builders)
@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())));
}