JAVA流什么时候会出现EOFException
我正在使用 DataInputStream 并且有一个关于 EOFExceptions 的问题。
根据java文档:
表示文件结束或结束 流已意外到达 输入期间。
这个异常主要是数据使用的 输入流以表示流结束。 请注意,许多其他输入操作 结束时返回一个特殊值 流而不是抛出 异常。
这是否意味着当生成 EOFException 时,流将永远不会再次打开? 这是否意味着您永远不应期望从中获得更多数据?
如果输出流连接到输入流并且调用了outputstream.close(),输入流会收到EOFException还是IOException?
IOException 描述为:
表示某些 I/O 异常的信号 排序已发生。 这门课是 产生的一般异常类别 由失败或中断的 I/O 操作。
输出流的关闭是否会在数据输入流端产生 EOFException 或 IOException?
I am working with a DataInputStream and had a question about EOFExceptions.
According to java docs:
Signals that an end of file or end of
stream has been reached unexpectedly
during input.This exception is mainly used by data
input streams to signal end of stream.
Note that many other input operations
return a special value on end of
stream rather than throwing an
exception.
Does this mean that when a EOFException is generated, the stream will not NEVER open again? Does it mean you should NEVER expect any more data from it ever?
If an outputstream is connected to an inputstream and outputstream.close() is called, will an inputstream receive the EOFException or an IOException?
An IOException is described as:
Signals that an I/O exception of some
sort has occurred. This class is the
general class of exceptions produced
by failed or interrupted I/O
operations.
Does a close on the outputstream produce either a EOFException or an IOException on the datainputstream side?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
关键词是意料之外。
如果您使用 DataInputStream 并读取 4 字节整数,但流中仅剩余 3 个字节,您将收到 EOFException。
但如果你在流末尾调用 read() ,你只会得到 -1 ,没有例外。
The key word is unexpected.
If you use DataInputStream and read a 4 byte integer but there were only 3 bytes remaining in the stream you'll get an EOFException.
But if you call read() at the end of stream you'll just get -1 back and no exception.
当到达流的末尾(文件末尾或对等点关闭连接)时:
read()
returns -1readLine()
returns nullreadXXX( )
对于任何其他 X 抛出EOFException
。该流仍然打开,但您应该停止读取并关闭它。
When you reach the end of a stream (end of file, or peer closes the connection):
read()
returns -1readLine()
returns nullreadXXX()
for any other X throwsEOFException
.The stream is still open, but you should stop reading from it and close it.
回答您问题的另一部分:是的,EOF 意味着流上不会再看到更多数据; 你应该关闭它。
Answering another part of your question: Yes, EOF means that no more data will be seen on the stream; you should close it.
EOFException 是 IOException 的子类。 如果您尝试从流中读取数据并且没有更多数据可供读取(例如,因为您的 DataInputStream 包裹在 FileInputStream 中,并且您尝试读取的字节数多于文件中剩余的字节数),则会抛出该错误。
EOFException is a subclass of IOException. It will be thrown if you attempt to read from the stream and there is no more data to be read (e.g. because your DataInputStream is wrapped around a FileInputStream and you're trying to read more bytes than are left in the file).
抛出 EOFException:
EOFException is thrown: