When will an EOFException occur in JAVA's streams

亡梦爱人 提交于 2019-11-27 05:16:16

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.

When you reach the end of a stream (end of file, or peer closes the connection):

  • read() returns -1
  • readLine() returns null
  • readXXX() for any other X throws EOFException.

The stream is still open, but you should stop reading from it and close it.

Answering another part of your question: Yes, EOF means that no more data will be seen on the stream; you should close it.

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).

Saili Waichal

EOFException is thrown:

  1. if there is no data in a STREAM but you are trying to read...eg read methods of chain streams like DataInputStream, ObjectInputStream, RandomAccessFile throw EOFException if they are trying to read from FileInputStream but the FileInputStream is empty
  2. or if the formats are not matching...eg if int is present and you are using readFloat() of DataInputStream
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!