2010-07-12 128 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