请注意,我们正在将流程输出逐行读取到我们的StringBuilder
中。由于 try-with-resources
语句,我们不需要手动关闭流。ProcessBuilder
类让我们将程序名称和参数数提交给其构造函数。
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class ProcessOutputExample
{
public static void main(String[] arguments) throws IOException,
InterruptedException
{
System.out.println(getProcessOutput());
}
public static String getProcessOutput() throws IOException, InterruptedException
{
ProcessBuilder processBuilder = new ProcessBuilder("java",
"-version");
processBuilder.redirectErrorStream(true);
Process process = processBuilder.start();
StringBuilder processOutput = new StringBuilder();
try (BufferedReader processOutputReader = new BufferedReader(
new InputStreamReader(process.getInputStream()));)
{
String readLine;
while ((readLine = processOutputReader.readLine()) != null)
{
processOutput.append(readLine + System.lineSeparator());
}
process.waitFor();
}
return processOutput.toString().trim();
}
}
指纹:
java version "1.8.0_45"
Java(TM) SE Runtime Environment (build 1.8.0_45-b15)
Java HotSpot(TM) 64-Bit Server VM (build 25.45-b02, mixed mode)