EOFException in Java is thrown when end of file is reached unexpectedly while processing the input. These exceptions are thrown while working the DataInputStream, ObjectInputStream and RandomAccessFile classes. All these classes are using one of the stream classes like FileInputStream for reading the data. When there is no data available in the stream by DataInputStream is trying to read some data, then this exception will be thrown. This is a subclass of IOException.
EOFException Example
This exception is thrown when you reach the end of a stream (end of file, or peer closes the connection):
- read() method returns -1
- readLine() method returns null
- readXXX() for any other X throws EOFException. Here X means the method name would be readInt, readFloat, etc. Say, when you are trying to read any of these methods, it would expect some specified length of streams in the underlying FileInputStream, if that is empty then EOFException will be thrown. Also when you are using readInt and only float is available in the file will throw the same exception.
Here is the example for an application which throws EOFException:
import java.io.DataInputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class ExceptionExample { public void testMethod1(){ File file = new File("test.txt"); DataInputStream dataInputStream = null; try{ dataInputStream = new DataInputStream(new FileInputStream(file)); while(true){ dataInputStream.readInt(); } }catch (EOFException e){ e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); } finally{ try{ if (dataInputStream != null){ dataInputStream.close(); } }catch (IOException e){ e.printStackTrace(); } } } public static void main(String[] args){ ExceptionExample instance1 = new ExceptionExample(); instance1.testMethod1(); } }
When you run the above program, you will get the following exception:
java.io.EOFException at java.io.DataInputStream.readInt(DataInputStream.java:392) at logging.simple.ExceptionExample.testMethod1(ExceptionExample.java:16) at logging.simple.ExceptionExample.main(ExceptionExample.java:36)
I have enforced the above program to throw the EOFException by making the while loop condition with true. This will make your program run even after reading all the data and throw the exception. Application programmer has to ensure that the data read from the stream is correct and closed when there is no more data in the stream
I hope this tutorial provided good idea on the scenarios when EOFException is thrown from a Java application. If you have any questions, please write it in the comments section.