读取 java exec 的输出

发布于 2024-12-15 21:12:47 字数 516 浏览 0 评论 0原文

你好,我有一些关于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。为什么?

Hello i have some question about java.
here is my code:

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);
}

in that code i'am trying to get a java version command execute is ok, but i can't read the output it just return null. Why?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

孤独患者 2024-12-22 21:12:47

使用 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);

Use getErrorStream().

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

EDIT:

You can use ProcessBuilder (and also read the documentation)

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);
一曲琵琶半遮面シ 2024-12-22 21:12:47

请注意,我们正在将流程输出逐行读取到 StringBuilder。由于 try-with-resources 声明我们不需要手动关闭流。 ProcessBuilder class 让我们向其构造函数提交程序名称和参数数量。

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)

Note that we're reading the process output line by line into our StringBuilder. Due to the try-with-resources statement we don't need to close the stream manually. The ProcessBuilder class let's us submit the program name and the number of arguments to its constructor.

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();
    }
}

Prints:

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)
水晶透心 2024-12-22 21:12:47

您已经拥有进程-对象(名称公关)。您可以获得输入、输出和错误流。在您的情况下,您需要 pr。 getInputStream()。从其中读取,它连接到过程的输出。

You already have the process-object (name pr). You can get the Input-, Output- and Errorstream. In your case you want pr.getInputStream(). Read from that, that is connected to the output of the process.

诗笺 2024-12-22 21:12:47

试试这个

public static final Pair<Integer,Integer> javaVersion(File file) throws IOException {
    final ProcessBuilder pb = new ProcessBuilder("java", "-version");
    pb.directory(new File(file.getCanonicalPath() + File.separator  + "bin"));
    pb.redirectErrorStream(true);

    // Call the test target
    final Process process = pb.start();
    final InputStream in = process.getInputStream();
    final InputStream err = process.getErrorStream();

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
    String s = bufferedReader.readLine();
    int start = s.indexOf('\"');
    int end = s.lastIndexOf('\"');
    String substring = s.substring(start + 1, end);
    String[] split = substring.split("\\.");

    return new Pair<>(Integer.parseInt(split[0]),Integer.parseInt(split[1]));
}

try this

public static final Pair<Integer,Integer> javaVersion(File file) throws IOException {
    final ProcessBuilder pb = new ProcessBuilder("java", "-version");
    pb.directory(new File(file.getCanonicalPath() + File.separator  + "bin"));
    pb.redirectErrorStream(true);

    // Call the test target
    final Process process = pb.start();
    final InputStream in = process.getInputStream();
    final InputStream err = process.getErrorStream();

    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(in,"UTF-8"));
    String s = bufferedReader.readLine();
    int start = s.indexOf('\"');
    int end = s.lastIndexOf('\"');
    String substring = s.substring(start + 1, end);
    String[] split = substring.split("\\.");

    return new Pair<>(Integer.parseInt(split[0]),Integer.parseInt(split[1]));
}
暗地喜欢 2024-12-22 21:12:47

我也遇到了这个问题,因为我没有正确设置 $JAVA_HOME 。 (我忘记了目录/主页)。
在我编辑 $JAVA_HOME,更新 Gradle JVM,并删除 .idea 目录以使用 gradle 重新构建后,效果很好。

I also suffered this issue because I didn't set $JAVA_HOME correctly. (I forgot Contents/Home).
After I edit $JAVA_HOME, update Gradle JVM, and remove .idea directory to re-build with gradle, It works well.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文