如何在Java中處理EOFException?
在某些情況下,讀取檔案內容時會到達檔案末尾,在這種情況下會丟擲EOFException異常。
尤其是在使用輸入流物件讀取資料時,會丟擲此異常。在其他情況下,到達檔案末尾時會丟擲特定值。
示例
讓我們考慮DataInputStream類,它提供了各種方法,例如readboolean()、readByte()、readChar()等,用於讀取原始值。使用這些方法從檔案讀取資料時,如果到達檔案末尾,則會丟擲EOFException異常。
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);
}
}
}執行時異常
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 {
//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");
}
}輸出
Data written successfully
以下是另一種在Java中處理EOFException的方法:
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
廣告
資料結構
網路
關係資料庫管理系統 (RDBMS)
作業系統
Java
iOS
HTML
CSS
Android
Python
C語言程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP