2

我想在我的 Java 程序中读取 c-Application 的输出流。iremoted(可在此处获得:http: //osxbook.com/software/iremoted/download/iremoted.c)是一个 C 应用程序,如果按下 Apple Remote 上的按钮,它会显示单独的行,如“0x19 已按下”。如果我启动 iremoted 程序,一切都运行良好,每次按下按钮时,这些单独的行都会显示在我的屏幕上。现在我想在我的 Java 应用程序中读取 c 应用程序的输出流,以处理 Java 项目中 Apple Remote 的输入。不幸的是,我不知道为什么没有输入被重新识别

我用一个简单的 HelloWorld.c 程序进行了尝试,我的程序在这种情况下按预期响应(打印出 HelloWorld)。

为什么它不适用于 iremoted 程序?

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();
    }
}

}
4

2 回答 2

3

stdout被缓冲,如果您不写入屏幕,它不会自动刷新。添加:

fflush(stdout);

后:

printf("%#lx %s\n", (UInt32)event.elementCookie,
    (event.value == 0) ? "depressed" : "pressed");
于 2012-08-14T17:20:47.823 回答
1

如果 hello world 程序有效,iremoted 可能会写入 stderr。在这种情况下,您会想要错误流。我不确定这如何适用于您的 hello world 案例 - 我认为您在这里做错了事:

 new InputStreamReader(process.getInputStream()); 

应该

 new InputStreamReader(process.getOutputStream());

或者

 new InputStreamReader(process.getErrorStream());
于 2012-08-14T17:13:35.207 回答