如何使 Java 类侦听“stdout”上的事件C 程序的
public static void main(String[] args) {
try {
String line;
InputStream stdout = null;
OutputStream stdin = null;
Process process = Runtime.getRuntime().exec("test.exe");
stdout = process.getInputStream ();
stdin = process.getOutputStream ();
line = "Hello World" + "\n";
stdin.write(line.getBytes() );
stdin.flush();
stdin.close();
BufferedReader brCleanUp =
new BufferedReader (new InputStreamReader (stdout));
while ((line = brCleanUp.readLine ()) != null) {
System.out.println ("[Stdout] " + line);
}
brCleanUp.close();
}
catch(Exception e){
System.out.println("Error\n");
}
}
上面的代码允许 Java 类在“test.exe”(C 程序)的标准输入中写入并读取其标准输出 现在,我如何创建一个 Java 类来侦听 C 程序标准输出上的事件。这是一个 Java 事件监听器,每次在 C 程序的 stdout 中写入新行时都会调用该监听器
public static void main(String[] args) {
try {
String line;
InputStream stdout = null;
OutputStream stdin = null;
Process process = Runtime.getRuntime().exec("test.exe");
stdout = process.getInputStream ();
stdin = process.getOutputStream ();
line = "Hello World" + "\n";
stdin.write(line.getBytes() );
stdin.flush();
stdin.close();
BufferedReader brCleanUp =
new BufferedReader (new InputStreamReader (stdout));
while ((line = brCleanUp.readLine ()) != null) {
System.out.println ("[Stdout] " + line);
}
brCleanUp.close();
}
catch(Exception e){
System.out.println("Error\n");
}
}
The code above allows a Java class to write in the stdin of "test.exe" (C program) and to read its stdout
Now, how can I make a Java Class which listens for the events on the stdout of a C program. That is a Java event listener that will be called each time a new line is written in the stdout of the C program
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您需要有一个单独的线程来阻止读取输入流。然后,它可以在主线程上触发事件(例如,对于 Swing GUI 使用 java.awt.EventQueue.invokeLater)。
You need to have a separate thread which blocks reading the input stream. It can then fire events on your main thread (for instance using
java.awt.EventQueue.invokeLater
for a Swing GUI).