如何使用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’t force our readers to sign up with us or submit their details either. Enjoy the free content
以上是如何使用Java中的RandomAccessFile读取.txt文件?的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

AI Hentai Generator
免费生成ai无尽的。

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

Java 8引入了Stream API,提供了一种强大且表达力丰富的处理数据集合的方式。然而,使用Stream时,一个常见问题是:如何从forEach操作中中断或返回? 传统循环允许提前中断或返回,但Stream的forEach方法并不直接支持这种方式。本文将解释原因,并探讨在Stream处理系统中实现提前终止的替代方法。 延伸阅读: Java Stream API改进 理解Stream forEach forEach方法是一个终端操作,它对Stream中的每个元素执行一个操作。它的设计意图是处
