首页 > Java > java教程 > 正文

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

WBOY
发布: 2023-09-08 20:13:02
转载
1136人浏览过

如何使用java中的randomaccessfile读取.txt文件?

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

Java中的java.io.RandomAccessFile类使您能够向随机访问文件读取/写入数据。

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

该类提供了各种方法来读取和写入文件。该类的readLine()方法从文件中读取下一行并以字符串形式返回。

立即学习Java免费学习笔记(深入)”;

使用该类的readLine()方法从文件中读取数据的步骤如下:

GNU make 中文手册 pdf版
GNU make 中文手册 pdf版

GNU makefile中文手册 pdf,文比较完整的讲述GNU make工具,涵盖GNU make的用法、语法。同时重点讨论如何为一个工程编写Makefile。阅读本书之前,读者应该对GNU的工具链和Linux的一些常用编程工具有一定的了解。诸如:gcc、as、ar、ld、yacc等本文比较完整的讲述GNU make工具,涵盖GNU make的用法、语法。重点讨论如何使用make来管理软件工程、以及如何为工程编写正确的Makefile。 本手册不是一个纯粹的语言翻译版本,其中对GNU make的一些语法

GNU make 中文手册 pdf版 2
查看详情 GNU make 中文手册 pdf版
  • 通过以字符串格式传递所需文件的路径来实例化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&rsquo;t force our readers to sign up with us or submit their details either.
Enjoy the free content
登录后复制

以上就是如何使用Java中的RandomAccessFile读取.txt文件?的详细内容,更多请关注php中文网其它相关文章!

java速学教程(入门到精通)
java速学教程(入门到精通)

java怎么学习?java怎么入门?java在哪学?java怎么学才快?不用担心,这里为大家提供了java速学教程(入门到精通),有需要的小伙伴保存下载就能学习啦!

下载
来源:tutorialspoint网
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn
最新问题
开源免费商场系统广告
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
关于我们 免责申明 举报中心 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号