简体   繁体   English

如何立即阅读Java InputStream?

[英]How to read Java InputStream without delay?

I have C++ program (feeder.exe), that prints some data: 我有C ++程序(feeder.exe),可以打印一些数据:

printf("%s\n", line);

In average it produces 20-30 lines per second, but not uniformly. 平均而言,它每秒产生20到30条线,但不一致。

I want to catch this data in Java program by running the exe from Java code: 我想通过从Java代码运行exe来在Java程序中捕获此数据:

package temp_read;    
import java.io.*;
public class Main {

    public static void main(String[] args) throws Throwable {
        Process p = Runtime.getRuntime().exec("d:/feeder.exe");
        InputStream is = p.getInputStream();
        BufferedReader in = new BufferedReader(new InputStreamReader(is));
        String line = null;
        while ((line = in.readLine()) != null) {
            System.out.println(System.currentTimeMillis() + "," + line);
        }
    }
}

But when I look into the output, I see that it receives a bulk of strings once per 3-5 seconds. 但是当我查看输出时,我发现它每3-5秒接收一次大量的字符串。

Question : how to receive the data from feeder.exe immediately without any delay when it prints to stdout? 问题 :打印到stdout时,如何立即从feeder.exe接收数据而没有任何延迟?

PS: not related question: How to stop the feeder.exe if I stop the java by Ctrl+C? PS:不相关的问题:如果我通过Ctrl + C停止Java,如何停止feeder.exe?

If redirected, stdout is probably buffered, meaning that the problem is in the C++ code and not on the Java side. 如果重定向,则可能会缓冲stdout,这意味着问题出在C ++代码中,而不是Java端。 The C++ process will buffer the output and flush several "printf"s at once, as soon as the buffer is full. 一旦缓冲区已满,C ++进程将缓冲输出并立即刷新多个“ printf”。

If you are able to modify the C++ software, try to do a fflush(stdout); 如果您能够修改C ++软件,请尝试执行fflush(stdout); after the printf to force the output buffer to be flushed. 在printf之后,强制刷新输出缓冲区。

The most likely cause is that the feeder.exe is not flushing its output stream regularly, and the data is sitting in its output buffer until the buffer fills and is written as a result. 最可能的原因是feeder.exe没有定期刷新其输出流,并且数据一直位于其输出缓冲区中,直到缓冲区填满并被写入为止。

If that is the cause, there is nothing you can do on the Java side to avoid this. 如果这是原因,那么在Java方面您无能为力。 The problem can only be fixed by modifying the feeder application. 该问题只能通过修改feeder应用程序来解决。


Note that if the data was in the "pipe" that connected the two processes, then reading on the Java side would get it. 请注意,如果数据位于连接两个进程的“管道”中,则在Java端读取将得到数据。 Assuming that the end-of-line had been written to the pipe, the readLine() call would deliver the line without blocking. 假定行尾已写入管道, readLine()调用将传递该行而不会阻塞。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM