如何在Java中读取DataInputStream到文件末尾,而无需捕获EOFException?


在某些情况下读取文件内容时,会到达文件末尾,在这种情况下会抛出EOFException。

特别是,在使用输入流对象读取数据时会抛出此异常。在其他情况下,到达文件末尾时会抛出特定值。

在DataInputStream类中,它提供了各种方法,例如readboolean()、readByte()、readChar()等,用于读取原始值。使用这些方法从文件中读取数据时,如果到达文件末尾,则会抛出EOFException。

示例

以下程序演示了如何在Java中处理EOFException。

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Scanner;
public class AIOBSample {
   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;
         ch = dis.readChar();
         System.out.print(ch);
      }
   }
}

输出

Enter a String:
hello how are you
helException in thread "main" lo how are youjava.io.EOFException
   at java.io.DataInputStream.readChar(Unknown Source)
   at MyPackage.AIOBSample.main(AIOBSample.java:27)

读取DataInputStream而无需捕获异常

您不能使用**DataInputStream**类读取文件内容而不到达文件末尾。如果需要,可以使用InputStream接口的其他子类。

示例

在下面的示例中,我们使用FileInputStream类而不是DataInputStream类重写了上面的程序,以从文件中读取数据。

import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Scanner;
public class AIOBSample {
   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
      File file = new File("D:\data.txt");
      FileInputStream fis = new FileInputStream(file);
      byte b[] = new byte[(int) file.length()];
      fis.read(b);
      System.out.println("contents of the file: "+new String(b));
   }
}

输出

Enter a String:
Hello how are you
contents of the file: H e l l o h o w a r e y o u

更新于:2020年7月2日

1K+ 次浏览

启动您的职业生涯

通过完成课程获得认证

开始
广告
© . All rights reserved.