如何在java中获得运行时执行的实时输出?

41ik7eoe  于 2021-07-03  发布在  Java
关注(0)|答案(1)|浏览(555)

这是我的密码:

Runtime runtime = Runtime.getRuntime();
    Process process = runtime.exec("cmd.exe /c kotlinc -script " + script.getAbsolutePath());
    process.waitFor();
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line = "";
    while ((line = bufferedReader.readLine()) != null){
        System.out.println(line);
    }

我想要的只是运行脚本的实时输出。有人知道怎么做吗?提前谢谢!

wooyq4lh

wooyq4lh1#

你的 process.waitFor() 调用是阻塞调用,仅在进程结束时解除阻塞,阻止流工作,因为进程结束时流将关闭。
在一个单独的线程中读取流,该线程称为 .waitFor() 或在调用之前从流中读取 .waitFor() ```
Runtime runtime = Runtime.getRuntime();
Process process = runtime.exec("cmd.exe /c kotlinc -script " + script.getAbsolutePath());
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = "";
while ((line = bufferedReader.readLine()) != null){
System.out.println(line);
}
int exitValue = process.waitFor();

顺便说一句,我会使用processbuilder来获取进程,而不是 `Runtime.getRuntime()` 

相关问题