读取 java exec 的输出

2022-09-01 02:28:06

你好,我有一些关于java的问题。这是我的代码:

public static void main(String[] args) throws Exception {
    Process pr = Runtime.getRuntime().exec("java -version");

    BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
    String line;
    while ((line = in.readLine()) != null) {
        System.out.println(line);
    }
    pr.waitFor();
    System.out.println("ok!");

    in.close();
    System.exit(0);
}

在该代码中,我试图让java版本命令执行是可以的,但我无法读取输出,它只是返回null。为什么?


答案 1

使用 getErrorStream()。

BufferedReader in = new BufferedReader(new InputStreamReader(pr.getErrorStream()));

编辑:

您可以使用 ProcessBuilder(也可以阅读文档)

ProcessBuilder   ps=new ProcessBuilder("java.exe","-version");

//From the DOC:  Initially, this property is false, meaning that the 
//standard output and error output of a subprocess are sent to two 
//separate streams
ps.redirectErrorStream(true);

Process pr = ps.start();  

BufferedReader in = new BufferedReader(new InputStreamReader(pr.getInputStream()));
String line;
while ((line = in.readLine()) != null) {
    System.out.println(line);
}
pr.waitFor();
System.out.println("ok!");

in.close();
System.exit(0);

答案 2

请注意,我们正在将流程输出逐行读取到我们的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)

推荐