ขณะอ่านเนื้อหาของไฟล์ ในบางสถานการณ์ จะถึงจุดสิ้นสุดของไฟล์ ในสถานการณ์เหล่านี้ จะมีการโยน EOFException
โดยเฉพาะ ข้อยกเว้นนี้จะถูกโยนขณะอ่านข้อมูลโดยใช้วัตถุ Input Stream ในสถานการณ์อื่น ค่าที่เฉพาะเจาะจงจะถูกส่งคืนเมื่อถึงจุดสิ้นสุดของไฟล์
ตัวอย่าง
พิจารณาคลาส DataInputStream ซึ่งให้เมธอดต่างๆ เช่น readBoolean(), readByte(), readChar() เป็นต้น เพื่ออ่านค่าประเภทพื้นฐาน ขณะอ่านข้อมูลจากไฟล์โดยใช้เมธอดเหล่านี้ เมื่อถึงจุดสิ้นสุดของไฟล์ จะมีการโยน EOFException
import java.io.DataInputStream; import java.io.FileInputStream; public class EOFExample { public static void main(String[] args) throws Exception { // อ่านจากไฟล์ที่สร้างไว้ข้างต้นโดยใช้เมธอด readChar() DataInputStream dis = new DataInputStream(new FileInputStream("D:\\data.txt")); while(true) { char ch; ch = dis.readChar(); System.out.print(ch); } } }ข้อยกเว้นรันไทม์
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)
การจัดการ EOFException
คุณไม่สามารถอ่านเนื้อหาของไฟล์โดยไม่ถึงจุดสิ้นสุดของไฟล์ได้โดยใช้คลาส DataInputStream หากต้องการ คุณสามารถใช้คลาสย่อยอื่นของอินเทอร์เฟซ InputStream
ตัวอย่าง
ในตัวอย่างต่อไปนี้ เราเขียนโปรแกรมข้างต้นใหม่โดยใช้คลาส FileInputStream แทน DataInputStream เพื่ออ่านข้อมูลจากไฟล์
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 { // อ่านข้อมูลจากผู้ใช้ byte[] buf = " Hello how are you".getBytes(); // เขียนลงไฟล์โดยใช้ 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"); } }ผลลัพธ์
Data written successfully
อีกวิธีหนึ่งในการจัดการ EOFException ใน 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) { } } } }ผลลัพธ์
Hello how are you End of file reached