且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

输入/输出流:流结束?

更新时间:2022-05-30 22:02:53

想象一个正在读取的文件.那里有流的结尾,文件的结尾.如果您尝试阅读更多内容,则根本无法阅读.但是,如果您有网络连接,则只需等待发送更多数据,就不需要结束流.

Think of a file being read. There is an end of stream there, the end of the file. If you try to read beyond that, you simply can't. If you have a network connection though, there doesn't need to be an end of stream if you simply wait for more data to be sent.

就文件而言,我们知道没有更多数据可供读取.在网络流的情况下,我们(通常)不会.

In the case of the file, we know for a fact that there is no more data to be read. In the case of a network stream we (usually) don't.

在没有更多数据可用时阻止 FileReader,在有数据时唤醒:简单的答案是:你不能.根本区别在于您主动读取文件,但是当您收听网络流时,您是被动读取的.当某些东西来自网络时,您的硬件会向操作系统发送一个短信号,然后操作系统将新数据提供给您的 JVM,然后 JVM 唤醒您的进程以读取新数据(可以这么说).但是我们没有文件,至少不是立即.

Blocking a FileReader when no more data is available, awakening when there is: the simple answer is: you can't. The fundamental difference is that you read a file actively, but when you listen to a network stream you read passively. When something comes from the network your hardware sends a short of signal to the Operating System, which then gives the new data to your JVM, and the JVM then awakens your process to read the new data (so to speak). But we don't have that with a file, at least not immediately.

一种可能的解决方法是为您拥有的 StreamReader 制作一个包装器,并在文件更改时通知一个侦听器,然后唤醒您进一步阅读.在 Java 7 中,您可以使用 WatchService.

A possible workaround would be to make a wrapper to the StreamReader you have, with a listener that is notified when the file is changed, which then awakens you to read further. In Java 7 you can use the WatchService.