EOFException तब फेंका जाता है जब इनपुट स्ट्रीम से पढ़ते समय फाइल/स्ट्रीम का अंत अप्रत्याशित रूप से पहुंच जाता है (उदाहरण: DataInputStream.readChar())।
समस्या उदाहरण
DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
while (true) {
char ch = dis.readChar(); // EOF पर EOFException फेंकता है
System.out.print(ch);
}हैंडलिंग दृष्टिकोण
1. Try-Catch के साथ EOFException पकड़ें
DataInputStream dis = new DataInputStream(new FileInputStream("data.txt"));
try {
while (true) {
char ch = dis.readChar();
System.out.print(ch);
}
} catch (EOFException e) {
System.out.println("\nEnd of file reached");
} finally {
dis.close();
}2. वैकल्पिक स्ट्रीम का उपयोग करें जो EOF को अलग तरीके से संकेत देते हैं
// FileInputStream.read() अंत पर -1 लौटाता है, अपवाद नहीं फेंकता
FileInputStream fis = new FileInputStream("data.txt");
int b;
while ((b = fis.read()) != -1) {
System.out.print((char) b);
}3. BufferedReader.readLine() - अंत पर null लौटाता है
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
String line;
while ((line = br.readLine()) != null) {
System.out.println(line);
}सर्वोत्तम अभ्यास
- बाइनरी डेटा के लिए
DataInputStreamके साथ try-catch का उपयोग करें। - टेक्स्ट के लिए
BufferedReaderयाScannerपसंद करें (कोई अपवाद नहीं)। - हमेशा finally या try-with-resources में स्ट्रीम बंद करें।