与另一个进程Java交互 [英] Interacting with another process Java
问题描述
我正在尝试与Java中的另一个进程进行交互。它是这样的......
I am trying to interact with another process in Java. It goes like this...
Runtime rt;
Process pr=rt.exec("cmd");
然后我使用...发送一些命令到进程...
then I send some commands to the process using...
BufferedReader processOutput = new BufferedReader(new InputStreamReader(pr.getInputStream()));
BufferedWriter processInput = new BufferedWriter(new OutputStreamWriter(pr.getOutputStream()));
processInput.write("gdb");
processInput.flush();
我现在不关心输出..所以我试着用它来忽略它
I don't care about the output for now.. so I try to ignore it using..
while(processOutput.readLine() != null);
但这个循环永远挂起。我知道这是因为进程仍在运行并且不发送空值。我现在不想终止它。我必须根据用户输入发送命令然后获得输出..
but this loops hangs forever. I know this is because process is still running and doesn't sends a null. I don't want to terminate it now. I have to send commands based on user Input and then get the output..
如何做到这一点?换句话说,我想在执行某些命令后刷新Process输出流或忽略它,并在我想要的时候读取它。
How to do this? In other words I want to flush the Process output stream or ignore it after executing some commands and read it only when I want to.
推荐答案
使用单独的线程读取输出。这样,只要有输出就会被读取,但不会阻止你。
Use a separate thread to read the output. This way, as long as there is output it will be read, but will not block you.
例如,创建这样一个类:
For example, create such a class:
public class ReaderThread extends Thread {
private BufferedReader reader = null;
public ReaderThread(BufferedReader reader) {
this.reader = reader;
}
@Override
public void run() {
String line = null;
try {
while ((line = reader.readLine()) != null) {
System.out.println(line);
}
}
catch(IOException exception) {
System.out.println("!!Error: " + exception.getMessage());
}
}
}
在您的主要课程中,代替 while(processOutput.readLine()!= null);
,请致电:
And in your main class, instead of while(processOutput.readLine() != null);
, call:
ReaderThread reader = new ReaderThread(processOutput);
reader.start();
这篇关于与另一个进程Java交互的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!