如何使用Java中的RandomAccessFile读取.txt文件?

通常,在将数据读取或写入文件时,只能从文件开头读取或写入数据。您不能从随机位置读取/写入。

java.io。Java中的RandomAccessFile类使您可以将数据读/写到随机访问文件。

此行为类似于带有索引的大型字节数组,或称为文件指针的光标,您可以使用getFilePointer()方法获取此指针的位置并使用该seek()方法进行设置。

此类提供了各种方法来读取和写入数据到文件。此类的readLine()方法从文件中读取下一行,并以String形式返回。

使用此类的readLine()方法从文件中读取数据-

  • 通过以String格式传递所需文件的路径来实例化File类。

  • 实例化StringBuffer类。

  • 通过传递上面创建的File对象和表示访问模式的String来实例化RandomAccessFile类(r:read,rw:read / write等。)

  • 在文件的位置小于其长度时迭代文件(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";
      //实例化File类
      File file = new File(filePath);
      //实例化StringBuffer-
      StringBuffer buffer = new StringBuffer();
      //实例化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:
(cainiaojc.com) 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