首页 > 编程知识 正文

java中为什么会出现EOF异常,java io eof exception

时间:2023-05-05 19:55:35 阅读:207224 作者:632

在某些情况下读取文件的内容时,在这种情况下将到达文件末尾,将引发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

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。