如何使用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); } }登录后复制