如何在Java中使用RandomAccessFile讀取.txt檔案?


通常情況下,在讀取或寫入檔案資料時,只能從檔案開頭讀取或寫入資料。無法從隨機位置讀取/寫入。

Java中的java.io.RandomAccessFile類允許您讀取/寫入隨機訪問檔案。

這類似於一個大型位元組陣列,帶有一個索引或游標,稱為檔案指標,您可以使用getFilePointer()方法獲取此指標的位置,並使用seek()方法設定它。

此類提供各種方法來讀取和寫入檔案資料。此類的readLine()方法讀取檔案中的下一行,並以字串形式返回。

要使用此類的readLine()方法從檔案讀取資料:

  • 透過以字串格式傳遞所需檔案的路徑來例項化File類。

  • 例項化StringBuffer類。

  • 透過傳遞上面建立的File物件和一個表示訪問模式的字串(r:讀取,rw:讀取/寫入等)來例項化RandomAccessFile類。

  • 在檔案位置小於其長度(length()方法)時迭代檔案。

  • 將每一行追加到上面建立的StringBuffer物件。

示例

import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
public class RandomAccessFileExample {
   public static void main(String args[]) throws IOException {
      String filePath = "D://input.txt";
      //Instantiating the File class
      File file = new File(filePath);
      //Instantiating the StringBuffer
      StringBuffer buffer = new StringBuffer();
      //instantiating the RandomAccessFile
      RandomAccessFile raFile = new RandomAccessFile(file, "rw");
      //Reading each line using the readLine() method
      while(raFile.getFilePointer() < raFile.length()) {
         buffer.append(raFile.readLine()+System.lineSeparator());
      }
      String contents = buffer.toString();
      System.out.println("Contents of the file: \n"+contents);
   }
}

輸出

Contents of the file:
Tutorials Point originated from the idea that there exists a class of readers who respond better 
to online content and prefer to learn new skills.
Our content and resources are freely available and we prefer to keep it that way to encourage 
our readers acquire as many skills as they would like to.
We don’t force our readers to sign up with us or submit their details either.
Enjoy the free content

更新於: 2019年10月14日

2K+ 次瀏覽

啟動您的職業生涯

完成課程獲得認證

開始學習
廣告
© . All rights reserved.