【问题标题】:Using Java to call Linux terminal: How to flush the output?使用 Java 调用 Linux 终端:如何刷新输出?
【发布时间】:2011-03-14 23:33:13
【问题描述】:

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在终端中写入文件?

提前致谢 E.E.

【问题讨论】:

    标签: java linux terminal flush


    【解决方案1】:

    这个问题是由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
    }
    

    【讨论】:

    • 小心这种方法。使用 exec() 时,stdout/stderr 流中潜伏着一些讨厌的东西。您确实需要在 waitFor() 阻塞时异步消耗输出/错误流,否则它可能永远不会返回,因为 stdout/err 缓冲区已填满并阻塞分叉进程。签出 apache commons-exec 以获得解决此问题的库。
    【解决方案2】:

    您可以等待该过程完成:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-11-05
      • 2021-12-30
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 1970-01-01
      相关资源
      最近更新 更多