What is EOFException in Java? How do we handle it?

While reading the contents of a file in certain scenarios the end of the file will be reached in such scenarios a EOFException is thrown.

Especially, this exception is thrown while reading data using the Input stream objects. In other scenarios a specific value will be thrown when the end of file reached.

Let us consider the DataInputStream class, it provides various methods such as readboolean(), readByte(), readChar() etc.. to read primitive values. While reading data from a file using these methods when the end of file is reached an EOFException is thrown.


Following program demonstrates how to handle the EOFException in Java.

 Live Demo

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Scanner;
public class Just {
   public static void main(String[] args) throws Exception {
      //Reading data from user
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter a String: ");
      String data = sc.nextLine();
      byte[] buf = data.getBytes();
      //Writing it to a file using the DataOutputStream
      DataOutputStream dos = new DataOutputStream(new FileOutputStream("D:\data.txt"));
      for (byte b:buf) {
      //Reading from the above created file using readChar() method
      DataInputStream dis = new DataInputStream(new FileInputStream("D:\data.txt"));
      while(true) {
         char ch;
         try {
            ch = dis.readChar();
         } catch (EOFException e) {
            System.out.println("End of file reached");
         } catch (IOException e) {}


Enter a String:
Hello how are you
Hello how are you
End of file reached