當 read() 方法在 java 中到達檔案末尾時會返回什麼值?


輸入流類的read()方法逐位元組讀取給定檔案的內容,並以整數形式返回讀取位元組的 ASCII 值。在讀取檔案時,如果它到達檔案末尾,則此方法將返回 -1。

示例

假設我們在當前目錄中有一個文字檔案 (sample.txt),其中有簡單的文字“Hello welcome”。以下 Java 程式使用 read() 方法逐位元組地讀取檔案內容,並列印為每個位元組返回的整數值。

由於我們沒有檢查檔案末尾,因此 read() 方法到達末尾,輸出的最後一個整數將為 -1。

import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class EndOfFileExample {
   public static void main(String[] args) {
      try{
         File file = new File("sample.txt");
         DataInputStream inputStream = new DataInputStream(new FileInputStream(file));
         System.out.println(file.length());
         for(int i=0; i<=file.length();i++) {
            int num = inputStream.read();
            System.out.println(num);
         }
      } catch(IOException ioe) {
         ioe.printStackTrace();
      }
   }
}

輸出

13
72
101
108
108
111
32
119
101
108
99
111
109
101
-1

更新於: 30-Jul-2019

1 千次觀看

開啟你的 職業生涯

完成課程,獲得認證

開始
廣告
© . All rights reserved.