问题描述
UPDATE:我发现了为什么这可能不起作用的关键部分!我使用 System.setOut(out);其中 out 是一个特殊的 PrintStream 到 JTextArea
这是代码,但我遇到的问题是信息只有在我结束过程后才会打印出来.
This is the code, but the issue I'm having is that the information is only printed out once I end the process.
public Constructor() {
main();
}
private void main() {
btnStart.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
ProcessBuilder builder = new ProcessBuilder("java", textFieldMemory.getText(), "-jar", myJar);
Process process = builder.start();
InputStream inputStream = process.getInputStream();
BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream), 1);
String line;
while ((line = bufferedReader.readLine()) != null) {
System.out.println(line);
}
inputStream.close();
bufferedReader.close();
} catch (IOException ioe) {
ioe.printStackTrace();
}
}
});
}
当前输出:
Line 1
Line 2
Line 3
Line 4
Line 5
这是正确的输出,但是当我结束这个过程时它只被打印为一个大块.
This is the correct output, but it is only being printed as one big block when I end the process.
有谁知道这是什么问题?如果是这样,您能帮我解释一下为什么会发生这种情况吗,提前致谢.
Does anyone know what the issue is? If so can you help explain to me why this is happening, thank-you in advance.
推荐答案
在单独的线程中处理进程的输出流可能会有所帮助.您还希望在继续您的逻辑之前明确等待流程结束:
Processing the output stream of the process in a separate thread might help here. You also want to explicitly wait for the process to end before continuing with your logic:
ProcessBuilder builder = new ProcessBuilder("java",
textFieldMemory.getText(), "-jar", myJar);
final Process process = builder.start();
final Thread ioThread = new Thread() {
@Override
public void run() {
try {
final BufferedReader reader = new BufferedReader(
new InputStreamReader(process.getInputStream()));
String line = null;
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
reader.close();
} catch (final Exception e) {
e.printStackTrace();
}
}
};
ioThread.start();
process.waitFor();
这篇关于从进程打印 Java InputStream的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!