Handle EOFException in Java



While reading the contents of a file using a Java program, we may reach the end of the file abruptly; in such cases, EOFException (End Of File) is thrown.

Especially, this exception occurs while reading data using the InputStream objects, such as DataInputStream. In other scenarios, a specific value will be thrown when the end of the file is reached.

Why Does the EOFException Occur

The EOFException occurs when a stream reaches the end of the file while reading its contents. If we 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 the file is reached, an EOFException is thrown.

Example

Assume we have a file named data.txt with the following contents -

Tutorials Point is a leading Ed Tech company striving to provide the best learning material on technical and non-technical subjects.

Now, when we try to read its contents using the readChar() method, it causes an EOFException -

import java.io.DataInputStream;
import java.io.FileInputStream;
public class Just {
   public static void main(String[] args) throws Exception {
      //Reading from the above created file using readChar() method
      DataInputStream dis = new DataInputStream(new FileInputStream("D:/data.txt"));
      while(true) {
         char ch;
         ch = dis.readChar();
         System.out.print(ch);
      }
   }
}

Runtime Exception

If you run the above program, it generates the following exception -

Tutorialspoint is a leading Ed Tech company striving to provide the best learning material on technical and non-technical subjects.Exception in thread "main" java.io.EOFException
   at java.base/java.io.DataInputStream.readFully(DataInputStream.java:210)
   at java.base/java.io.DataInputStream.readChar(DataInputStream.java:363)
   at Just.main(Just.java:9)

Handling EOFException

You cannot read the contents of a file without reaching the end of the file using the DataInputStream class. If you want, you can use other sub-classes of the InputStream interface. There are different ways to handle EOFException in Java, and they are -

  • Using try-catch to catch EOFException

  • Using FileInputStream.available() to check the file size before reading

  • Using BufferReader with null check(for character type files)

  • Using ObjectInputStream for Objects

Using try-catch to catch EOFException

The try-catch block stops the program from throwing an exception when the end of the file is reached. Instead of throwing an error, the catch block handles EOFException. When reading from a file using methods like readChar(), an EOFException occurs at the end. We can use a try-catch block to handle the EOFException and stop the abrupt termination of the program.

import java.io.DataInputStream;
import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
public class HandlingEOF {
   public static void main(String[] args) throws Exception {
      DataInputStream dis = new DataInputStream(new FileInputStream("D:\data.txt"));
      while (true) {
         char ch;
         try {
            ch = dis.readChar();
            System.out.print(ch);
         } catch (EOFException e) {
            System.out.println("");
            System.out.println("End of file reached");
            break;
         } catch (IOException e) {}
      }
   }
}

Output

Hello how are you
End of file reached

Using FileInputStream.available()

The available() method of the FileInputStream class returns the number of remaining bytes in the current file.It returns 0 when there is no more data to read. Instead of reading until an exception occurs, we can use this method to verify the remaining contents of the file.

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;

public class HandleEOFUsingAvailable {
   public static void main(String[] args) throws Exception {
      //  Write some data to a file
      String text = "Hello how are you";
      DataOutputStream dos = new DataOutputStream(new FileOutputStream("data.txt"));
      for (byte b: text.getBytes()) {
         dos.writeChar(b);
      }
      dos.close();
      System.out.println("Data written successfully.");

      //  Read data using available() to avoid EOFException
      DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
      while (dis.available() > 0) {
         char ch = dis.readChar();
         System.out.print(ch);
      }
      dis.close();
   }
}

Output

Data written successfully.
Hello how are you

Using BufferReader with null check

When reading text data line by line using BufferedReader, the readLine() method returns a line of text and null if it reaches the end of the file. It reads lines in a loop until readLine() returns null. 

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class HandleEOFBufferedReader {
   public static void main(String[] args) {
      try (BufferedReader br = new BufferedReader(new FileReader("data.txt"))) {
         String line;
         while ((line = br.readLine()) != null) {
            System.out.println(line);
         }
         System.out.println("End of file reached.");
      } catch (IOException e) {
         System.out.println("Error reading file: " + e.getMessage());
      }
   }
}

Output

Hello how are you
End of file reached.

Using ObjectInputStream for Objects

ObjectInputStream is used for deserializing objects (converting data from a stored format, like back into a Java object) in Java. While reading objects from a file or stream, when the end of the stream is reached, it can throw an EOFException. This exception indicates that no more objects can be read, so handling it properly is important.

When using ObjectInputStream.readObject(), you need to catch the EOFException to know when the end of the file or stream is reached. It uses a loop to keep reading objects until the EOFException is thrown, showing that there are no more objects left to deserialize.

import java.io.EOFException;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ClassNotFoundException;

public class HandleEOFUsingObjectInputStream {
   public static void main(String[] args) {
      try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("data.obj"))) {
         while (true) {
            try {
               Object obj = ois.readObject(); // Reading objects from the file
               System.out.println("Read object: " + obj);
            } catch (EOFException e) {
               System.out.println("\nEnd of file reached.");
               break; // Stop reading when EOF is reached
            } catch (ClassNotFoundException e) {
               System.out.println("Class not found: " + e.getMessage());
            }
         }
      } catch (IOException e) {
         System.out.println("IOException occurred: " + e.getMessage());
      }
   }
}

Output

Read object: Hello
Read object: How
Read object: are
Read object: you?
End of file reached.
Updated on: 2025-04-18T18:14:21+05:30

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements