gpt4 book ai didi

java - 线程在终止之前不会输出流

转载 作者:行者123 更新时间:2023-12-02 03:47:11 25 4
gpt4 key购买 nike

我正在尝试打印运行外部 jar 的实时输出,它在线程中运行并且 jar 确实得到执行,问题是输出在线程终止之前不会打印。

public void run() {
Process proc = null;
try {

proc = Runtime.getRuntime().exec("java -jar A.jar");
InputStream in = proc.getInputStream();
InputStream err = proc.getErrorStream();

BufferedInputStream bis = new BufferedInputStream(in);
BufferedInputStream bes = new BufferedInputStream(err);

String iss = IOUtils.toString(in, "UTF8");
String ess = IOUtils.toString(err, "UTF8");

System.out.println(iss);
System.out.println(ess);

} catch (IOException e) {
e.printStackTrace();
this.interrupt();
}
}

最佳答案

您需要在单独的线程中运行它们,以便同时读取它们。

public void run() {
try {
Process proc = Runtime.getRuntime().exec("/home/martin/test.py");
InputStream in = proc.getInputStream();
InputStream err = proc.getErrorStream();

Thread tIn = new Thread(() -> {
try {
while (true) {
int ch;
ch = in.read();
if (ch < 0)
break;
System.out.print((char) ch);
}
} catch (IOException e) {
e.printStackTrace();
}
});

Thread tErr = new Thread(() -> {
try {
while (true) {
int ch;
ch = err.read();
if (ch < 0)
break;
System.err.print((char) ch);
}
} catch (IOException e) {
e.printStackTrace();
}
});

tIn.start();
tErr.start();

try {
tIn.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
try {
tErr.join();
} catch (InterruptedException e) {
e.printStackTrace();
}

// this.interrupt();
} catch (IOException e) {
e.printStackTrace();
// this.interrupt();
}
}

这是单个函数中快速而肮脏的版本。当然,最好编写一个包装该功能的类。

关于java - 线程在终止之前不会输出流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56797309/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com