Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Cách xử lý EOFException trong Java

Khi đọc nội dung tệp trong một số tình huống, cuối tệp sẽ được đạt đến và khi đó EOFException được ném ra.

Đặc biệt, ngoại lệ này được ném khi đọc dữ liệu bằng các đối tượng InputStream. Trong các tình huống khác, một giá trị cụ thể sẽ được trả về khi đạt đến cuối tệp.

Ví dụ

Xét lớp DataInputStream, nó cung cấp các phương thức như readBoolean(), readByte(), readChar() v.v. để đọc các giá trị nguyên thủy. Khi đọc dữ liệu từ tệp bằng các phương thức này, khi đạt đến cuối tệp, EOFException sẽ được ném.

import java.io.DataInputStream;
import java.io.FileInputStream;

public class EOFExample {
    public static void main(String[] args) throws Exception {
        // Đọc từ tệp bằng phương thức readChar()
        DataInputStream dis = new DataInputStream(new FileInputStream("D:\\data.txt"));
        while (true) {
            char ch;
            ch = dis.readChar();
            System.out.print(ch);
        }
    }
}

Ngoại lệ lúc chạy

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)

Xử lý EOFException

Bạn không thể đọc nội dung tệp mà không đạt đến cuối tệp khi sử dụng lớp DataInputStream. Nếu muốn, bạn có thể sử dụng các lớp con khác của giao diện InputStream.

Ví dụ: Sử dụng FileInputStream thay vì 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 {
        // Ghi dữ liệu vào tệp
        byte[] buf = " Hello how are you".getBytes();
        DataOutputStream dos = new DataOutputStream(new FileOutputStream("D:\\data.txt"));
        for (byte b : buf) {
            dos.writeChar(b);
        }
        dos.flush();
        System.out.println("Ghi dữ liệu thành công");
    }
}

Kết quả

Ghi dữ liệu thành công

Cách khác để xử lý EOFException trong 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("Đã đạt cuối tệp");
                break;
            } catch (IOException e) {
                // Xử lý IOException khác
            }
        }
    }
}

Kết quả

Hello how are you
Đã đạt cuối tệp