2010-07-12 125 views
5

1)我用Java調用Linux終端運行foo.exe的和輸出保存到一個文件:使用Java調用Linux終端:如何刷新輸出?

String[] cmd = {"/bin/sh", "-c", "foo >haha.file"}; 
    Runtime.getRuntime().exec(cmd); 

2)問題是,當我打算在後面的代碼讀取haha.file ,它還沒有被寫入:

File f=new File("haha.file"); // return true 
in = new BufferedReader(new FileReader("haha.file")); 
reader=in.readLine(); 
System.out.println(reader);//return null 

3)只有在程序完成後,haha.file纔會被寫入。我只知道如何沖洗「作家」,但不知道如何沖洗。喜歡這個。 如何強制java在終端中寫入文件?

在此先感謝 E.E.

回答

0

您可以等待該過程的完成:

Process p = Runtime.getRuntime().exec(cmd); 
int result = p.waitFor(); 

或者使用p.getInputStream()直接從過程的標準輸出讀。

2

此問題是由Runtime.exec的異步性質引起的。 foo正在執行一個獨立的過程。您需要致電Process.waitFor()以確保文件已被寫入。

String[] cmd = {"/bin/sh", "-c", "foo >haha.file"}; 
Process process = Runtime.getRuntime().exec(cmd); 
// .... 
if (process.waitFor() == 0) { 
    File f=new File("haha.file"); 
    in = new BufferedReader(new FileReader("haha.file")); 
    reader=in.readLine(); 
    System.out.println(reader); 
} else { 
    //process did not terminate normally 
} 
+1

要小心這種方法。使用exec()時,潛伏着stdout/stderr流。當waitFor()被阻塞時,你確實需要異步地消耗輸出/錯誤流,否則它可能永遠不會返回,因爲stdout/err緩衝區填滿並阻塞分叉進程。簽出解決這個問題的lib的apache commons-exec。 – 2010-07-12 20:19:19