2010-09-14 79 views
2

我寫,我需要對整個運行的應用程序的生命週期在後臺運行的過程的Java應用程序運行的Java運行時進程。獲取背景

這是我有:

Runtime.getRuntime().exec("..(this works ok).."); 
Process p = Runtime.getRuntime().exec("..(this works ok).."); 
InputStream is = p.getInputStream(); 
InputStreamReader isr = new InputStreamReader(is); 
BufferedReader br = new BufferedReader(isr); 

所以,基本上我打印出每個br.readLine()

,我是不知道的事情是如何在我的應用程序中實現此代碼,因爲無論我把它(與Runnable接口),它會阻止其他代碼運行(如預期)。

我用了Runnable,螺紋,SwingUtilities類的,並沒有什麼作品...

任何幫助,將不勝感激:)

回答

1

可以讀取輸入流(即br.readLine())在一個線程。這樣,它總是在後臺運行。

我們已經在我們的應用中實現這一點的方式大致如下圖所示:

業務邏輯,即您可以調用腳本的地方:

// Did something... 

InvokeScript.execute("sh blah.sh"); // Invoke the background process here. The arguments are taken in processed and executed. 

// Continue doing what you were doing 

InvokeScript.execute()看起來像如下:

InvokeScript.execute(String args) { 
// Process args, convert them to command array or whatever is comfortable 

Process p = Runtime.getRuntime().exec(cmdArray); 

ReaderThread rt = new ReaderThread(p.getInputStream()); 
rt.start(); 
} 

ReaderThread應該繼續讀取您開始的進程的輸出,只要它持續。

請注意,上面只是一個僞代碼。

+0

感謝pavanlimo,關於何時何地啓動Process = Runtime.getRuntime()。exec(? – phillyville 2010-09-14 16:59:24

+0

請參閱我上面的編輯 – pavanlimo 2010-09-14 17:13:53

+0

感謝一堆pavanlimo,我測試了瀏覽器上的代碼和它就像一個魅力,但我實際上是尋找東西的Java桌面應用程序。一次你知道InvokeScript和ReaderThread的Java中的等價物? – phillyville 2010-09-14 18:08:48