- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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.
Example
Following program demonstrates how to handle the EOFException in 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; 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) { dos.writeChar(b); } dos.flush(); //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(); System.out.print(ch); } catch (EOFException e) { System.out.println(""); System.out.println("End of file reached"); break; } catch (IOException e) {} } } }
Output
Enter a String: Hello how are you Hello how are you End of file reached
Advertisements