Partner – Moderne – NPI EA (cat=Spring Boot)
announcement - icon

Refactor Java code safely — and automatically — with OpenRewrite.

Refactoring big codebases by hand is slow, risky, and easy to put off. That’s where OpenRewrite comes in. The open-source framework for large-scale, automated code transformations helps teams modernize safely and consistently.

Each month, the creators and maintainers of OpenRewrite at Moderne run live, hands-on training sessions — one for newcomers and one for experienced users. You’ll see how recipes work, how to apply them across projects, and how to modernize code with confidence.

Join the next session, bring your questions, and learn how to automate the kind of work that usually eats your sprint time.

Course – Black Friday 2026 – NPI EA – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – before_post_content
announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

1. Overview

In this tutorial, we’ll look at the java.io.EOFException, a special type of IOException that we may encounter when working with files in Java.

We’ll first understand the cause of this exception and then discuss how we can resolve it.

2. Why Does EOFException Occur?

Before diving into the details, let’s first understand what this exception means.

EOF in EOFException stands for “End Of File”. It signals that the program has reached the end of the file while reading its contents.

Typically, the exception is thrown while reading data using the input stream objects. For instance, the DataInputStream class provides methods such as readChar(), readInt(), readDouble(), etc., to read values from a stream. In such a scenario, an EOFException is thrown when the end of the stream is reached.

So, one of the most common causes behind the exception is the program reaching the end of the file while reading it.

3. EOFException Example

Now that we understand EOFException better let’s see how it looks in practice.

In this example program, integer values are indefinitely read from an input and printed to standard output. 

public class EOFExceptionDemo {
    public static void readInput() throws Exception {
        InputStream is = new ByteArrayInputStream("123".getBytes());
        DataInputStream in = new DataInputStream(is);
        while (true) {
            char value = (char) in.readByte();
            System.out.println("Input value: " + value);
        }
    }
}

As expected, this function throws an EOFException after printing the following output:

Input value: 1

Input value: 2

Input value: 3

java.io.EOFException

Next, let’s take a look at how we can resolve this exception.

4. Handling EOFException

In the above example, EOFException is thrown at the following line:

int value = in.readInt()

One thing to note about the DataInputStream class is that we can’t read the contents of the input without reaching an end. So, we can use a try-catch block to handle the exception. Also, as values are read inside an infinite loop, we need to break from it when the exception is thrown.

Below is the updated code:

public class EOFExceptionDemo2 {
    public static void readInput() throws Exception {
        InputStream is = new ByteArrayInputStream("123".getBytes());
        DataInputStream in = new DataInputStream(is);
        while (true) {
            try {
                char value = (char)in.readByte();
                System.out.println("Input value: " + value);
            } catch (EOFException e) {
                System.out.println("End of file");
                break;
            }
        }      
    }
}

Now, with the addition of the try-catch block, here’s the code output:

Input value: 1

Input value: 2

Input value: 3

End of file

As we can see, the program now exits successfully without any exceptions.

5. Preventing EOFException

An alternative to handling the exception is preventing it from happening in the first place. This can be done using the Scanner class, which provides the hasNext() method to check if the input has reached its end before reading it. As a result, the EOFException is never thrown. However, other exceptions like NoSuchElementException, InputMismatchException, and IllegalStateException can still occur.

Here’s the code for preventing the EOFException:

public class EOFExceptionDemo3 {
    public static void readInput() {
        InputStream is = new ByteArrayInputStream("1 2 3".getBytes());
        Scanner sc = new Scanner(is);
        while (sc.hasNextInt()) {
            int value = sc.nextInt();
            System.out.println("Input value: " + value);
        }
        System.out.println("End of file");
        sc.close();
    }
}

Note that the output for the above code remains the same without throwing and catching the EOFException.

6. Conclusion

In this article, we examined why the EOFException occurs and how to handle it using a try-catch block.

The code backing this article is available on GitHub. Once you're logged in as a Baeldung Pro Member, start learning and coding on the project.
Partner – Moderne – NPI EA (tag=Refactoring)
announcement - icon

Modern Java teams move fast — but codebases don’t always keep up. Frameworks change, dependencies drift, and tech debt builds until it starts to drag on delivery. OpenRewrite was built to fix that: an open-source refactoring engine that automates repetitive code changes while keeping developer intent intact.

The monthly training series, led by the creators and maintainers of OpenRewrite at Moderne, walks through real-world migrations and modernization patterns. Whether you’re new to recipes or ready to write your own, you’ll learn practical ways to refactor safely and at scale.

If you’ve ever wished refactoring felt as natural — and as fast — as writing code, this is a good place to start.

Course – Black Friday 2026 – NPI EA – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW

Course – Black Friday 2026 – NPI – main – after_post_content

announcement - icon

Yes, we're now running our Black Friday Sale. All Courses are 33% off until 1st December, 2026 at 17:00 Romania time:

>> EXPLORE ACCESS NOW