Read from another process' output stream

2019-02-26 15:30发布

i wanted to read the output-stream of a c-Application in my Java program. iremoted (available here: http://osxbook.com/software/iremoted/download/iremoted.c) is a C-Application that puts out seperate lines like "0x19 pressed" if a button on my Apple Remote is pressed. If i start the iremoted program everything is doing well and these separate lines are shown on my screen everytime I pressed a button. Now I wanted to read the output-stream of the c-application in my Java application to process inputs of the Apple Remote in Java projects. Unfortunately i don't know why no input is regocnized?

I tried it with a simple HelloWorld.c program and my program responded as intended in this case (prints out HelloWorld).

Why doensn't it work with the iremoted program?

public class RemoteListener {


public void listen(String command) throws IOException {

    String line;
    Process process = null;
    try {
        process = Runtime.getRuntime().exec(command);
    } catch (Exception e) {
        System.err.println("Could not execute program. Shut down now.");
        System.exit(-1);
    }

    Reader inStreamReader = new InputStreamReader(process.getInputStream());
    BufferedReader in = new BufferedReader(inStreamReader);

    System.out.println("Stream started");
    while((line = in.readLine()) != null) {
        System.out.println(line);
    }
    in.close();
    System.out.println("Stream Closed");
}




public static void main(String args[]) {
    RemoteListener r = new RemoteListener();
    try {
        r.listen("./iremoted"); /* not working... why?*/
        // r.listen("./HelloWorld"); /* working fine */
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

}

2条回答
你好瞎i
2楼-- · 2019-02-26 15:50

stdout is buffered and it's not automatically flushed if you are not writing to screen. Add:

fflush(stdout);

after:

printf("%#lx %s\n", (UInt32)event.elementCookie,
    (event.value == 0) ? "depressed" : "pressed");
查看更多
ら.Afraid
3楼-- · 2019-02-26 16:05

iremoted is likely writing to stderr if a hello world program works. You would want the error stream in that case. I'm not sure how this works for your hello world case - I think you're doing the wrong thing here:

 new InputStreamReader(process.getInputStream()); 

should be

 new InputStreamReader(process.getOutputStream());

or

 new InputStreamReader(process.getErrorStream());
查看更多
登录 后发表回答