如何从不断更新的 InputStream 中读取

How to read from InputStream that is constantly updating

我正在 Java 中开发一个应用程序,它基本上只是通过 GUI 收集用户的输入,并将此数据提供给执行某些文件系统操作的 python 脚本。此 python 脚本通过 Java 进程 class 执行。每个脚本只是将一些数据打印到它的标准输出,当我调用 process.getInputStream().

时,我在主 java 应用程序中解析这些数据

我有一个 python 脚本,它基本上对日志文件执行 tail -f 并逐行打印。我的 java 程序使用来自该特定进程的 InputStream 解析此输出。但是,我觉得它非常慢。我将此日志附加到 JavaFX TextArea,在执行 python 脚本后通常需要大约 20 秒,我的 java 程序开始接收任何内容,但是当我 运行 python 脚本本身,运行 符合预期。

到目前为止我已经尝试过:使用缓冲 reader 像这样解析它:

InputStream is = this.currentTask.getInputStream();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
String line;
while (this.currentTask.isAlive()){
   line = reader.readLine();
   if (line != null){
           final String finalLine = line;
           // JavaFX stuff so that the appending is on the main thread
           Platform.runLater(() -> output.appendText(finalLine + "\n"));
           continue;
   }
   // wait for the log to be updated 
   Thread.sleep(100);
}

当我使用调试器逐行执行时,它在 line = reader.readLine(); 部分卡住了很长时间。将读取方法切换为 BufferedReader 提供的另一种读取方法(如使用指定的字符缓冲区读取)根本没有帮助。

知道可能是什么问题吗?

编辑: 添加了 MCVE

Java 程序:

public static void main(String[] args) {
    Process process = null;
    try {
        process = Runtime.getRuntime().exec("python" + " " + "main.py");
    } catch (IOException e) {
        e.printStackTrace();
    }
    try {
        InputStream is = process.getInputStream();
        BufferedReader reader = new BufferedReader(new InputStreamReader(is, StandardCharsets.UTF_8));
        String line;
        while (process.isAlive()){
            line = reader.readLine();
            if (line != null){
                System.out.println(line);
                continue;
            }
            // wait for the log to be updated
            Thread.sleep(100);

        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
}

Python 程序:

import time

i = 0
while True:
    print("Output ", i)
    i += 1
    time.sleep(0.5)

我注意到当我从 python 脚本中删除睡眠时,整个事情都正常进行。然而,在真正的应用程序中,睡眠是需要的。

好的,我刚刚解决了它。感谢 this SO 问题。

Java 不是问题,python 只是没有足够频繁地刷新其输出,Java 没有什么可读的,就是这样。我必须手动刷新我的 python print() 函数,一切正常。