如何在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
广告