搜尋
首頁Javajava教程如何使用Java中的RandomAccessFile讀取.txt檔案?

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

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

Java中的java.io.RandomAccessFile類別可讓您向隨機存取檔案讀取/寫入資料。

這類似於具有索引或遊標(稱為檔案指標)的大型位元組數組,您可以使用getFilePointer()方法來取得該指標的位置,並使用seek()方法設定該位置。

該類別提供了各種方法來讀取和寫入檔案。該類別的readLine()方法從檔案中讀取下一行並以字串形式傳回。

使用該類別的readLine()方法從檔案讀取資料的步驟如下:

  • 透過以字串格式傳遞所需文件的路徑來實例化File類別。

  • 實例化StringBuffer類別。

  • 透過傳遞上述建立的File物件和表示存取模式的字串來實例化RandomAccessFile類別(r:讀取,rw:讀取/寫入等)。

  • 在檔案的位置小於其長度(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&rsquo;t force our readers to sign up with us or submit their details either.
Enjoy the free content

以上是如何使用Java中的RandomAccessFile讀取.txt檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:tutorialspoint。如有侵權,請聯絡admin@php.cn刪除

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

AI Hentai Generator

AI Hentai Generator

免費產生 AI 無盡。

熱工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

記事本++7.3.1

記事本++7.3.1

好用且免費的程式碼編輯器

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

EditPlus 中文破解版

EditPlus 中文破解版

體積小,語法高亮,不支援程式碼提示功能

Dreamweaver CS6

Dreamweaver CS6

視覺化網頁開發工具