Java中EOFException是什么?我们如何处理它?
在某些情况下读取文件内容时将达到文件末尾,在这些情况下会引发EOFException。
特别地,在使用输入流对象读取数据时会引发此异常。在其他情况下,达到文件末尾时将引发特定值。
让我们考虑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 {
//Reading data from user
Scanner sc = new Scanner(System.in);
System.out.println("Enter a String: ");
String data = sc.nextLine();
byte[] buf = data.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();
//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
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C编程
C++
C#
MongoDB
MySQL
JavaScript
PHP