使用Java调用Linux终端:如何刷新输出?
1)我使用Java调用Linux终端来运行foo.exe并将输出保存在文件中:
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在终端中写入文件?
提前致谢 电子工程
1) I'm using Java to call Linux terminal to run foo.exe and save the output in a file:
String[] cmd = {"/bin/sh", "-c", "foo >haha.file"};
Runtime.getRuntime().exec(cmd);
2) The problem is when I plan to read haha.file later in the code, it hasn't been written yet:
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) Only after the program is done will the haha.file be written. I only know how to flush "Writers" but don't know how to flush sth. like this.
How can I force java to write the file in the terminal?
Thanks in advance
E.E.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
此问题是由 运行时.exec。
foo
正在单独的进程中执行。您需要调用 Process.waitFor() 确保文件已写入。This problem is caused by the asynchronous nature of Runtime.exec.
foo
is being executed in a seperate process. You need to call Process.waitFor() to insure the file has been written.您可以等待该过程完成:
或者使用 p.getInputStream() 直接从该过程的标准输出中读取。
You can either wait for the completion of the process:
Or use the p.getInputStream() to read directly from the standard output of the process.