2012-08-14 58 views
1

我想在我的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)。

爲什麼doensn't它與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(); 
    } 
} 

} 
+0

如何iremoted打開它的輸出流?你確定它是直接寫入其stdout而不是stderr或終端? – 2012-08-14 17:15:52

+0

無論如何,我編輯了值得注意的部分fprintf(stdout,.....)。 – 2012-08-14 18:16:18

回答

3

stdout被緩衝,如果你沒有寫入屏幕,它不會自動刷新。地址:

fflush(stdout); 

後:

printf("%#lx %s\n", (UInt32)event.elementCookie, 
    (event.value == 0) ? "depressed" : "pressed"); 
+1

你是我的新天主<3 – 2012-08-14 18:07:03

+0

否則,我可以達到相同的輸出,而不是編輯C程序的來源? – 2012-08-14 18:14:53

+0

@BlackCurrant看看答案[這裏](http://stackoverflow.com/questions/1408678/getting-another-programs-output-as-input-on-the-fly) – 2012-08-14 18:34:48

1

iremoted很可能寫入標準錯誤,如果一個Hello World程序的工作。在這種情況下你會想要錯誤流。我不知道這是如何工作的您的hello world情況下 - 我認爲你在這裏做了錯誤的事情:

new InputStreamReader(process.getInputStream()); 

應該

new InputStreamReader(process.getOutputStream()); 

new InputStreamReader(process.getErrorStream()); 
+1

new InputStreamReader()將InputStream的一個實例作爲參數,不能將其轉換爲OutputStream。 – stuchl4n3k 2014-02-11 14:23:27

相關問題