Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When will an EOFException occur in JAVA's streams

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?

like image 722
jbu Avatar asked Mar 19 '09 22:03

jbu


People also ask

How do I fix EOF error in Java?

Handling EOFExceptionYou cannot read contents of a file without reaching end of the file using the DataInputStream class. If you want, you can use other sub classes of the InputStream interface.

What happens when the method close is invoked on a stream?

close() method closes this stream and releases any system resources associated with the stream.


2 Answers

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.

like image 73
Pyrolistical Avatar answered Sep 18 '22 18:09

Pyrolistical


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.

like image 26
user207421 Avatar answered Sep 20 '22 18:09

user207421