简体   繁体   中英

How to make a Java class listening for events on the “stdout” of a C program

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

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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM