Java中的EOFException是什么?我们该如何处理?
在某些情况下读取文件的内容时,在这种情况下将到达文件末尾,将引发EOFException。
特别是,在使用Input流对象读取数据时抛出此异常。在其他情况下,到达文件末尾时将抛出特定值。
让我们考虑DataInputStream类,它提供了各种方法,如readboolean(),readByte(),readChar()等等。阅读原始值。当使用这些方法从文件读取数据时,到达文件末尾时,将引发EOFException。
示例
以下程序演示了如何在Java中处理EOFException。
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 {
//从用户读取数据
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String: ");
String data = sc.nextLine();
byte[] buf = data.getBytes();
//将其写入文件
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) {}
}
}
}输出结果
Enter a String: Hello how are you Hello how are you End of file reached
热门推荐
10 广西考试祝福语结婚简短
11 猪年祝福语简短小孩
12 元旦祝福语送长辈简短
13 恭喜二宝祝福语简短
14 祝福语暖心话简短
15 国庆中秋祝福语简短兄弟
16 朋友订婚的祝福语简短
17 送弟弟中秋祝福语简短
18 爱生日祝福语简短独特