- EOFException Example in Java
- EOFException Example
- About Krishna Srinivasan
- How to Fix the EOFException in Java.io
- What Causes EOFException
- EOFException Example
- How to Fix EOFException
- Track, Analyze and Manage Errors With Rollbar
- How to handle EOFException in java?
- Example
- Runtime Exception
- Handling EOFException
- Example
- Output
- Output
- JavaMadeSoEasy.com (JMSE)
- What is hierarchy of java.lang. EOFException?
- EOFException is Checked (compile time exceptions) and UnChecked (RuntimeExceptions) in java ?
- java.lang.EOFException is a Checked (compile time) Exception in java.
- What is EOFException in java?
- Example/Programs /Scenarios where EOFException may be thrown in java>
- /** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
EOFException Example in Java
EOFException in Java is thrown when end of file is reached unexpectedly while processing the input. These exceptions are thrown while working the DataInputStream, ObjectInputStream and RandomAccessFile classes. All these classes are using one of the stream classes like FileInputStream for reading the data. When there is no data available in the stream by DataInputStream is trying to read some data, then this exception will be thrown. This is a subclass of IOException.
EOFException Example
This exception is thrown when you reach the end of a stream (end of file, or peer closes the connection):
- read() method returns -1
- readLine() method returns null
- readXXX() for any other X throws EOFException. Here X means the method name would be readInt, readFloat, etc. Say, when you are trying to read any of these methods, it would expect some specified length of streams in the underlying FileInputStream, if that is empty then EOFException will be thrown. Also when you are using readInt and only float is available in the file will throw the same exception.
Here is the example for an application which throws EOFException:
import java.io.DataInputStream; import java.io.EOFException; import java.io.File; import java.io.FileInputStream; import java.io.IOException; public class ExceptionExample < public void testMethod1()< File file = new File("test.txt"); DataInputStream dataInputStream = null; try< dataInputStream = new DataInputStream(new FileInputStream(file)); while(true)< dataInputStream.readInt(); >>catch (EOFException e) < e.printStackTrace(); >catch (IOException e) < e.printStackTrace(); >finally < try< if (dataInputStream != null)< dataInputStream.close(); >>catch (IOException e) < e.printStackTrace(); >> > public static void main(String[] args) < ExceptionExample instance1 = new ExceptionExample(); instance1.testMethod1(); >>
When you run the above program, you will get the following exception:
java.io.EOFException at java.io.DataInputStream.readInt(DataInputStream.java:392) at logging.simple.ExceptionExample.testMethod1(ExceptionExample.java:16) at logging.simple.ExceptionExample.main(ExceptionExample.java:36)
I have enforced the above program to throw the EOFException by making the while loop condition with true. This will make your program run even after reading all the data and throw the exception. Application programmer has to ensure that the data read from the stream is correct and closed when there is no more data in the stream
I hope this tutorial provided good idea on the scenarios when EOFException is thrown from a Java application. If you have any questions, please write it in the comments section.
About Krishna Srinivasan
He is Founder and Chief Editor of JavaBeat. He has more than 8+ years of experience on developing Web applications. He writes about Spring, DOJO, JSF, Hibernate and many other emerging technologies in this blog.
How to Fix the EOFException in Java.io
The java.io.EOFException is a checked exception in Java that occurs when an end of file or end of stream is reached unexpectedly during input. This exception is mainly used by data input streams to signal end of stream.
Since EOFException is a checked exception, it must be explicitly handled in methods that can throw this exception — either by using a try-catch block or by throwing it using the throws clause.
What Causes EOFException
While reading the contents of a file or stream using DataInputStream objects, if the end of the file or stream is reached unexpectedly, an EOFException is thrown. Methods of the DataInputStream class that are used to read data such as readBoolean() , readByte() and readChar() can throw this exception.
Many other input operations return a special value on end of file or stream rather than throwing an exception.
EOFException Example
Here’s an example of a EOFException thrown when trying to read all characters from an input file:
import java.io.DataInputStream; import java.io.FileInputStream; import java.io.IOException; public class EOFExceptionExample < public static void main(String[] args) < DataInputStream inputStream = null; try < inputStream = new DataInputStream(new FileInputStream("myfile.txt")); while (true) < inputStream.readChar(); >> catch (IOException ioe) < ioe.printStackTrace(); >finally < try < inputStream.close(); >catch (IOException ioe) < ioe.printStackTrace(); >> > >
In the above example, the contents of a file with the name myfile.txt are read in an infinite loop using the DataInputStream.readChar() method. When the readChar() method is called at the end of the file, an EOFException is thrown:
java.io.EOFException at java.base/java.io.DataInputStream.readChar(DataInputStream.java:369) at EOFExceptionExample.main(EOFExceptionExample.java:13)
How to Fix EOFException
Since EOFException is a checked exception, a try-catch block should be used to handle it. The try block should contain the lines of code that can throw the exception and the catch block should catch and handle the exception appropriately.
The above example can be updated to handle the EOFException in a try-catch block:
import java.io.DataInputStream; import java.io.EOFException; import java.io.FileInputStream; import java.io.IOException; public class EOFExceptionExample < public static void main(String[] args) < DataInputStream inputStream = null; try < inputStream = new DataInputStream(new FileInputStream("myfile.txt")); while (true) < try < inputStream.readChar(); >catch (EOFException eofe) < System.out.println("End of file reached"); break; >catch (IOException ioe) < ioe.printStackTrace(); >> > catch (IOException ioe) < ioe.printStackTrace(); >finally < try < inputStream.close(); >catch (IOException ioe) < ioe.printStackTrace(); >> > >
Here, the inputStream.readChar() method call is placed in a try block and the EOFException is caught inside the catch block. When an EOFException occurs at the end of the file, it is handled and a break statement is used to break out of the loop.
Track, Analyze and Manage Errors With Rollbar
Managing errors and exceptions in your code is challenging. It can make deploying production code an unnerving experience. Being able to track, analyze, and manage errors in real-time can help you to proceed with more confidence. Rollbar automates error monitoring and triaging, making fixing Java errors easier than ever. Sign Up Today!
How to handle EOFException in java?
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.
Example
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.
import java.io.DataInputStream; import java.io.FileInputStream; public class EOFExample < 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
Hello how are youException in thread "main" java.io.EOFException at java.io.DataInputStream.readChar(Unknown Source) at SEPTEMBER.remaining.EOFExample.main(EOFExample.java:11)
Handling EOFException
You cannot read contents of a file without reaching end of the file using the DataInputStream class. If you want, you can use other sub classes of the InputStream interface.
Example
In the following example we have rewritten the above program using FileInputStream class instead of DataInputStream to read data from a file.
import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Scanner; public class AIOBSample < public static void main(String[] args) throws Exception < //Reading data from user byte[] buf = " Hello how are you".getBytes(); //Writing it to a file using the DataOutputStream DataOutputStream dos = new DataOutputStream(new FileOutputStream("D:\data.txt")); for (byte b:buf) < dos.writeChar(b); >dos.flush(); System.out.println("Data written successfully"); > >
Output
Data written successfully
Following is another way to handle EOFException in Java −
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
JavaMadeSoEasy.com (JMSE)
Solution 1) You may persist some count in file during serialization process to find out exactly how many object were actually serialized and simply use for loop in place of while loop in deserialization process.
What is hierarchy of java.lang. EOFException?
EOFException is Checked (compile time exceptions) and UnChecked (RuntimeExceptions) in java ?
java.lang.EOFException is a Checked (compile time) Exception in java.
What is EOFException in java?
EOFException is the End of file Exception. Many input streams through EOFException to indicate end of file (Few Java Api doesn’t provide any elegant solution to signify end the file ) . EOFException could be thrown >
During use of RandomAccessFile , by using seek method we can move to random position, if seek is set beyond the length the file and we try to read from there than java.io.EOFException is thrown.
Example/Programs /Scenarios where EOFException may be thrown in java>
Create object of ObjectOutput and give its reference variable name oout and call writeObject() method and pass our employee object as parameter [ oout.writeObject(object1) ]
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
return «Employee [id background-color: transparent; color: black; font-family: Consolas; font-size: 13.333333333333332px; font-style: normal; font-variant: normal; font-weight: 400; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;»> + id + «, name background-color: transparent; color: black; font-family: Consolas; font-size: 13.333333333333332px; font-style: normal; font-variant: normal; font-weight: 400; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;»> + name + «]» ;
Create object of ObjectInput and give it’s reference variable name oin and call readObject() method [ oin.readObject() ]
In the above program when file is read till end using readObject() in while loop then EOFException is thrown. Java Api doesn’t provide any elegant solution to signify end the file.
By using seek method we can move to random position, if seek is set beyond the length the file and we try to read from there than java.io.EOFException is thrown.
Note : Before executing below program, remove everything from c:/myFile.txt for better understanding of program
Or preferably you may delete this file because if file doesn’t exist than RandomAccessFile will create new file.
System. out .println( «Data written in » + » background-color: transparent; color: black; font-family: Consolas; font-size: 13.333333333333332px; font-style: normal; font-variant: normal; font-weight: 400; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;»>+data);
System. out .println( «Data read from file background-color: transparent; color: black; font-family: Consolas; font-size: 13.333333333333332px; font-style: normal; font-variant: normal; font-weight: 400; text-decoration: none; vertical-align: baseline; white-space: pre-wrap;»>+data);
During deserialization process when file is read till end using readObject() in while loop then EOFException is thrown as we saw in DeSerialization program. Java Api doesn’t provide any elegant solution to signify end the file.
So, we’ll try to address the problem because catching EOFException and interpreting it as EOF is not the elegant solution because sometimes you may fail to detect a normal EOF of a file that has been truncated.
Solution 1) You may persist some count in file during serialization process to find out exactly how many object were actually serialized and simply use for loop in place of while loop in deserialization process.
Write instance of EofIndicatorClass at EOF during serialization to indicate EOF during deSerialization process.
If oin.readObject() returns instanceof EofIndicatorClass that means it’s EOF , exit while loop and EOFException will not be thrown.