2

i wanted to read the output-stream of a c-Application in my Java program. iremoted (available here: Link) 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();
    }
}

}
Glorfindel
  • 21,988
  • 13
  • 81
  • 109
AirUp
  • 426
  • 1
  • 8
  • 18

2 Answers2

3

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");
Piotr Praszmo
  • 17,928
  • 1
  • 57
  • 65
  • Can I achieve the same output otherwise, not editing the source of the C-Program? – AirUp Aug 14 '12 at 18:14
  • @BlackCurrant look at the answers [here](http://stackoverflow.com/questions/1408678/getting-another-programs-output-as-input-on-the-fly) – Piotr Praszmo Aug 14 '12 at 18:34
1

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());
Chris K
  • 11,996
  • 7
  • 37
  • 65
  • 1
    new InputStreamReader() takes an instance of InputStream as argument, that can not be cast to OutputStream. – stuchl4n3k Feb 11 '14 at 14:23