如何从 java 中的运行时执行获取实时输出?
How to get an live output from runtime execution in java?
这是我的代码:
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);
}
我想要的只是 运行 脚本的实时输出。有人知道怎么做吗?
您的 process.waitFor()
调用是一个阻塞调用,只有在进程结束时才会解除阻塞,从而阻止您的流工作,因为流将在进程结束时关闭。
在您调用 .waitFor()
的单独线程中从流中读取,或者在调用 .waitFor()
[=15= 之前 从流中读取]
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()
这是我的代码:
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);
}
我想要的只是 运行 脚本的实时输出。有人知道怎么做吗?
您的 process.waitFor()
调用是一个阻塞调用,只有在进程结束时才会解除阻塞,从而阻止您的流工作,因为流将在进程结束时关闭。
在您调用 .waitFor()
的单独线程中从流中读取,或者在调用 .waitFor()
[=15= 之前 从流中读取]
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()