本文介绍了输入/输出流:流的结束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直想知道:流的结束是什么?

I was always wondering: What is the end of a stream?

在java.io包中的大多数readLine方法的javadoc中,你可以读到如果到达流的末尾,则返回null - 尽管我实际上从未得到过null,因为大多数流(在我经常使用的网络流的情况下)只是阻止程序执行,直到将某些内容写入流中在远程端

In the javadoc of most readLine methods in the java.io package, you can read that "this returns null if the end of the stream is reached" - though I never actually got a null, as most streams (in the case of a network stream that I use most often) just block the program execution until something is written into the stream on the remote end

是否有办法以实际的非异常抛出方式强制执行这种行为?我只是好奇...

Are there ways to enforce this acutal behavior happening in an actual non-exception throwing way? I am simply curious ...

推荐答案

想想正在阅读的文件。那里有一个流的结尾,文件的结尾。如果你试图超越它,你就是不能。如果您有网络连接,如果您只是等待发送更多数据,则不需要结束流。

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中,您可以使用。

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.

这篇关于输入/输出流:流的结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 08:00