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 生日广州男生祝福语简短