Sotirios-Efstathios Maneas

About Sotirios-Efstathios Maneas

Sotirios-Efstathios (Stathis) Maneas is a postgraduate student at the Department of Informatics and Telecommunications of The National and Kapodistrian University of Athens. His main interests include distributed systems, web crawling, model checking, operating systems, programming languages and web applications.

java.io.EOFException – How to solve EOFException

In this tutorial we will discuss about the EOFException in Java. This exception indicates the the end of file (EOF), or the end of stream has been reached unexpectedly. Also, this exception is mainly used by DataInputStreams, in order to signal the end of stream. However, notice that other input operations may return a special value upon the end of a stream, instead of throwing an EOFException.

The EOFException class extends the IOException class, which is the general class of exceptions produced by failed, or interrupted I/O operations. Moreover, it implements the Serializable interface. Also, it is defined as a checked exception and thus, it must be declared in a method, or a constructor’s throws clause.

Finally, the EOFException exists since the 1.0 version of Java.

The Structure of EOFException

Constructors

  • EOFException()
  • Creates an instance of the EOFException class, setting null as its message.

  • EOFException(String s)
  • Creates an instance of the EOFException class, using the specified string as message. The string argument indicates the name of the class that threw the error.

The EOFException in Java

DataInputStreams provide methods that can read primitive Java data types from an underlying input stream in a machine-independent way. An application writes data, by using the methods provided by the OutputStream class, or the DataOutputStream class.

Specifically, primitive types can be read by an application, using one of the following methods:

  • readBoolean() – Reads one input byte and returns true if that byte is nonzero, false if that byte is zero.
  • readByte() – Reads and returns one input byte.
  • readChar() – Reads two input bytes and returns a char value.
  • readDouble() – Reads eight input bytes and returns a double value.
  • readFloat() – Reads four input bytes and returns a float value.
  • readInt() – Reads four input bytes and returns an int value.
  • readLong() – Reads eight input bytes and returns a long value.
  • readShort() – Reads two input bytes and returns a short value.
  • readUnsignedByte() – Reads one input byte and returns it as a zero-extended int value. The integer value resides in the range [0, 255].
  • readUnsignedShort() – Reads two input bytes and returns them as an int value. The integer value resides in the range [0, 65535].

For a list of all available methods, take a closer look on the DataInputStream class.

The following example reads all characters from an input file:

EOFExceptionExample.java:

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

public class EOFExceptionExample {
	
	//The name of the input file.
	private final static String FILENAME = "input.txt";
	
	private static void writeToFile() throws IOException {
		DataOutputStream out = new DataOutputStream(new FileOutputStream(FILENAME));
		
		//Write a string to the stream.
		String str = "Hello from Java Code Geeks!";
		for(int i = 0; i < str.length(); ++i)
			out.writeChar(str.charAt(i));
		
		//Close the data stream.
		out.close();
		
		return;
	}
	
	public static void main(String[] args) {
		DataInputStream input = null;
		try {
			//Write some integers to the file.
			writeToFile();
			
			// Read all characters, until an EOFException is thrown.
			input = new DataInputStream(new FileInputStream(FILENAME));
			while(true) {
				char num;
				try {
					num = input.readChar();
					System.out.println("Reading from file: " + num);
				}
				catch (EOFException ex1) {
					break; //EOF reached.
				}
				catch (IOException ex2) {
					System.err.println("An IOException was caught: " + ex2.getMessage());
					ex2.printStackTrace();
				}
			}
		}
		catch (IOException ex) {
			System.err.println("An IOException was caught: " + ex.getMessage());
			ex.printStackTrace();
		}
		finally {
			try {
				// Close the input stream.
				input.close();
			}
			catch(IOException ex) {
				System.err.println("An IOException was caught: " + ex.getMessage());
				ex.printStackTrace();
			}
		}
	}
}

In this example we first, write a string to a file and then, use the readChar() method to read all written characters one-by-one.

A sample execution is shown below:

Reading from file: H
Reading from file: e
Reading from file: l
Reading from file: l
Reading from file: o
Reading from file:  
Reading from file: f
Reading from file: r
Reading from file: o
Reading from file: m
Reading from file:  
Reading from file: J
Reading from file: a
Reading from file: v
Reading from file: a
Reading from file:  
Reading from file: C
Reading from file: o
Reading from file: d
Reading from file: e
Reading from file:  
Reading from file: G
Reading from file: e
Reading from file: e
Reading from file: k
Reading from file: s
Reading from file: !

Once the EOFException is thrown, we only have to break from the reading loop and then, close the stream.

Download the Eclipse Project

This was a tutorial about the EOFException in Java.

Download
You can download the full source code of this example here: EOFExceptionExample.zip.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.
Examples Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Examples Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Examples Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close