Read Also: [Fixed] java.util.regex.PatternSyntaxException in Java
[Fixed] java.io.EOFException
As always, first, we will produce the java.io.EOFException before moving on to the solution.Example 1: Producing the exception by calling readXXX() methods of DataInputStream class
You will get this exception if you are trying to read the characters from an input file and reaches the end of the stream (end of file/ peer closes connection) as shown below in the example:
import java.io.*; public class EOFExceptionExample { static final String dataFile = "data.txt"; public static void main(String args[]) { try { DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile))); while(true) {double data = dis.readChar();} } catch(IOException e) { e.printStackTrace(); } } }
Output:
java.io.EOFException
at java.io.DataInputStream.readChar(DataInputStream.java:365)
at EOFExceptionExample.main(EOFExceptionExample.java:12)
Explanation
In the above example, we are trying to read the contents of a file named data.txt in an infinite loop using the DataInputStream readChar() method. EOFException is thrown if the input stream reaches the end of the file and still tries to read from the stream. DataInputStream class methods such as readChar(), readInt(), readFloat(), readBoolean(), readByte() etc. can throw this exception.
Solution
As we know java.io.EOFException is a checked exception, the try-catch block should be used to handle it.
import java.io.*; public class EOFExceptionExample { static final String dataFile = "data.txt"; public static void main(String args[]) { try { DataInputStream dis = new DataInputStream(new BufferedInputStream(new FileInputStream(dataFile))); while(true) {try {double data = dis.readChar(); } catch(EOFException eof) { System.out.println("Reached end of file"); break; } } } catch(IOException e) { e.printStackTrace(); } } }
Output:
Reached end of file
In the above example, the dis.readChar() method is placed in a try block and inside the corresponding catch block, we have handled the EOFException. We have also used the break statement to break out of the loop.
That's all for today. Please mention in the comments if you have any questions related to how to fix java.io.EOFException in Java with examples.