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