问题描述
我正在使用 Runtime.getRuntime().exec
像这样从另一个 Java 应用程序运行 Java 程序
I'm running a Java program from another Java application using Runtime.getRuntime().exec
like this
Process p1 = Runtime.getRuntime().exec("javac test.java");
Process p2 = Runtime.getRuntime().exec("java test");
test.java 的内容
The content of the test.java
import java.io.*;
class test
{
public static void main(String args[])
{
Scanner sc = new Scanner(System.in);
String s = sc.nextLine();
System.out.println(s);
}
}
我想处理p2
过程的输入、输出和错误流.我确实捕获了 test.java
的输出,但是,我不知道如何处理输出和错误.
I want to handle Input, Output and Error stream of the process p2
.I did capture of the output of the test.java
, however, I do not know how to handle output and error.
这是我的代码:
try {
String s = "";
InputStream istr = p2.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(istr));
BufferedReader bre = new BufferedReader
(new InputStreamReader(p2.getErrorStream()));
while ((s = br.readLine()) != null) {
System.out.println(s);
}
br.close();
while ((s = bre.readLine()) != null) {
System.out.println(s);
}
bre.close();
p2.waitFor();
} catch (IOException ex) {
ex.printStackTrace();
} catch (Exception err) {
err.printStackTrace();
}
上面的代码可以很好地捕获test.java
的输出.但是它不显示test.java的错误.
The code above works fine for capturing the output of the test.java
. But it does not display error of the test.java.
你能给我一个示例代码来解决这个问题并处理输出流或分享想法吗?提前致谢
Could you please give me a sample code for fixing this problem and handling output stream or share idea? Thanks in advance
推荐答案
我一直使用的解决方案是创建一个单独的线程来读取其中一个流
The solution I've always used is to create a separate thread to read one of the streams
所以,在你的情况下应该是这样的
So, in your case it should be something like
String s = "";
InputStream istr = p2.getInputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(istr));
BufferedReader bre = new BufferedReader
(new InputStreamReader(p2.getErrorStream()));
new Thread(new Runnable() {
@Override
public void run() {
while ((s = br.readLine()) != null) {
System.out.println(s);
}
}
}).start();
new Thread(new Runnable() {
@Override
public void run() {
while ((s = bre.readLine()) != null) {
System.out.println(s);
}
}
}).start();
// when you are finished close streams
这篇关于从运行时进程java捕获错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!