输入/输出流:流结束? [英] Input/Output Stream : End of Stream?

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

问题描述

我一直在想:流的结尾是什么?

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

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆