使用Java调用Linux终端:如何刷新输出?

发布于 2024-09-09 00:26:12 字数 501 浏览 5 评论 0原文

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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

神回复 2024-09-16 00:26:12

此问题是由 运行时.execfoo 正在单独的进程中执行。您需要调用 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
}

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.

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
}
不打扰别人 2024-09-16 00:26:12

您可以等待该过程完成:

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

或者使用 p.getInputStream() 直接从该过程的标准输出中读取。

You can either wait for the completion of the process:

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

Or use the p.getInputStream() to read directly from the standard output of the process.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文