通常,在讀取或寫入檔案時,您只能從檔案的開頭讀取或寫入資料。您無法從隨機位置讀取/寫入。
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’t force our readers to sign up with us or submit their details either. Enjoy the free content
以上是如何使用Java中的RandomAccessFile讀取.txt檔案?的詳細內容。更多資訊請關注PHP中文網其他相關文章!