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

更新於: 30-Jul-2019

3000+瀏覽量

開啟您的職業生涯

完成課程並取得認證。

開始
廣告
© . All rights reserved.