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 婆婆高寿祝福语大全简短