RandomAccessFile使用小结
本文是基于Linux环境运行,读者阅读前需要具备一定Linux知识
RandomAccessFile是Java输入/输出流体系中功能最丰富的文件内容访问类,既可以读取文件内容,也可以向文件输出数据。与普通的输入/输出流不同的是,RandomAccessFile支持跳到文件任意位置读写数据,RandomAccessFile对象包含一个记录指针,用以标识当前读写处的位置,当程序创建一个新的RandomAccessFile对象时,该对象的文件记录指针对于文件头(也就是0处),当读写n个字节后,文件记录指针将会向后移动n个字节。除此之外,RandomAccessFile可以自由移动该记录指针
RandomAccessFile包含两个方法来操作文件记录指针:
- long getFilePointer():返回文件记录指针的当前位置
- void seek(long pos):将文件记录指针定位到pos位置
RandomAccessFile类在创建对象时,除了指定文件本身,还需要指定一个mode参数,该参数指定RandomAccessFile的访问模式,该参数有如下四个值:
- r:以只读方式打开指定文件。如果试图对该RandomAccessFile指定的文件执行写入方法则会抛出IOException
- rw:以读取、写入方式打开指定文件。如果该文件不存在,则尝试创建文件
- rws:以读取、写入方式打开指定文件。相对于rw模式,还要求对文件的内容或元数据的每个更新都同步写入到底层存储设备,默认情形下(rw模式下),是使用buffer的,只有cache满的或者使用RandomAccessFile.close()关闭流的时候儿才真正的写到文件
- rwd:与rws类似,只是仅对文件的内容同步更新到磁盘,而不修改文件的元数据
代码1-1
import java.io.IOException;
import java.io.RandomAccessFile; public class RandomAccessRead { public static void main(String[] args) {
if (args == null || args.length == 0) {
throw new RuntimeException("请输入路径");
}
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(args[0], "r");
System.out.println("RandomAccessFile的文件指针初始位置:" + raf.getFilePointer());
raf.seek(100);
byte[] bbuf = new byte[1024];
int hasRead = 0;
while ((hasRead = raf.read(bbuf)) > 0) {
System.out.print(new String(bbuf, 0, hasRead));
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (raf != null) {
raf.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} }
代码1-1运行结果:
root@lejian:/home/software/.io# cat article
Unexpected Benefits of Drinking Hot Water
Reasons To Love An Empowered Woman
Reasons Why It’s Alright To Feel Lost In A Relationship
Signs You’re Uber Smart Even If You Don’t Appear to Be
Differences Between Positive People And Negative People
Sex Before Marriage: 5 Reasons Every Couple Should Do It
root@lejian:/home/software/.io# java RandomAccessRead article
RandomAccessFile的文件指针初始位置:0
ght To Feel Lost In A Relationship
Signs You’re Uber Smart Even If You Don’t Appear to Be
Differences Between Positive People And Negative People
Sex Before Marriage: 5 Reasons Every Couple Should Do It
代码1-2使用RandomAccessFile来追加文件内容,RandomAccessFile先获取文件的长度,再将指针移到文件的末尾,再将要插入的内容插入到文件
代码1-2
import java.io.IOException;
import java.io.RandomAccessFile; public class RandomAccessWrite { public static void main(String[] args) {
if (args == null || args.length == 0) {
throw new RuntimeException("请输入路径");
}
RandomAccessFile raf = null;
try {
String[] arrays = new String[] { "Hello Hadoop", "Hello Spark", "Hello Hive" };
raf = new RandomAccessFile(args[0], "rw");
raf.seek(raf.length());
raf.write("追加内容:\n".getBytes());
for (String arr : arrays) {
raf.write((arr + "\n").getBytes());
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (raf != null) {
raf.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} }
代码1-2运行结果:
root@lejian:/home/software/.io# cat text
Hello spring
Hello Hibernate
Hello Mybatis
root@lejian:/home/software/.io# java RandomAccessWrite text
root@lejian:/home/software/.io# cat text
Hello spring
Hello Hibernate
Hello Mybatis
追加内容:
Hello Hadoop
Hello Spark
Hello Hive
RandomAccessFile如果向文件的指定的位置插入内容,则新输出的内容会覆盖文件中原有的内容。如果需要向指定位置插入内容,程序需要先把插入点后面的内容读入缓冲区,等把需要的插入数据写入文件后,再将缓冲区的内容追加到文件后面,代码1-3为在文件指定位置插入内容
代码1-3
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile; public class InsertContent { public static void main(String[] args) {
if (args == null || args.length != 3) {
throw new RuntimeException("请分别输入操作文件、插入位置和插入内容");
}
FileInputStream fis = null;
FileOutputStream fos = null;
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(args[0], "rw");
File tmp = File.createTempFile("tmp", null);
tmp.deleteOnExit();
fis = new FileInputStream(tmp);
fos = new FileOutputStream(tmp);
raf.seek(Long.parseLong(args[1]));
byte[] bbuf = new byte[64];
int hasRead = 0;
while ((hasRead = raf.read(bbuf)) > 0) {
fos.write(bbuf, 0, hasRead);
}
raf.seek(Long.parseLong(args[1]));
raf.write("\n插入内容:\n".getBytes());
raf.write((args[2] + "\n").getBytes());
while ((hasRead = fis.read(bbuf)) > 0) {
raf.write(bbuf, 0, hasRead);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
try {
if (fis != null) {
fis.close();
}
if (fos != null) {
fos.close();
}
if (raf != null) {
raf.close();
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
} }
代码1-3运行结果:
root@lejian:/home/software/.io# cat text
To love oneself is the beginning of a lifelong romance.
Change your life today. Don't gamble on the future, act now, without delay.
Health is the thing that makes you feel that now is the best time of the year.
The very essence of romance is uncertainty.
Your time is limited, so don’t waste it living someone else’s life.
root@lejian:/home/software/.io# java InsertContent text 100 "Success covers a multitude of blunders."
root@lejian:/home/software/.io# cat text
To love oneself is the beginning of a lifelong romance.
Change your life today. Don't gamble on the
插入内容:
Success covers a multitude of blunders.
future, act now, without delay.
Health is the thing that makes you feel that now is the best time of the year.
The very essence of romance is uncertainty.
Your time is limited, so don’t waste it living someone else’s life.
RandomAccessFile使用小结的更多相关文章
- JAVA(三)JAVA常用类库/JAVA IO
成鹏致远 | lcw.cnblog.com |2014-02-01 JAVA常用类库 1.StringBuffer StringBuffer是使用缓冲区的,本身也是操作字符串的,但是与String类不 ...
- Java之RandomAccessFile小结
今天跟大家分享一下javase中的关于I/O的操作: 有时我们需要在文件的末尾追加一些内容,在这时用RandomAccessFile就很好. 这个类有两个构造方法: RandomAccessFile( ...
- 通过扩展RandomAccessFile类使之具备Buffer改善I/O性能--转载
主体: 目前最流行的J2SDK版本是1.3系列.使用该版本的开发人员需文件随机存取,就得使用RandomAccessFile类.其I/O性能较之其它常用开发语言的同类性能差距甚远,严重影响程序的运行效 ...
- RandomAccessFile类——高效快捷地读写文件
RandomAceessFile类 RandomAccessFile类是一个专门读写文件的类,封装了基本的IO流,在读写文件内容方面比常规IO流更方便.更灵活.但也仅限于读写文件,无法像IO流一样,可 ...
- 在对文件进行随机读写,RandomAccessFile类,如何提高其效率
花1K内存实现高效I/O的RandomAccessFile类 JAVA的文件随机存取类(RandomAccessFile)的I/O效率较低.通过分析其中原因,提出解决方案.逐步展示如何创建具备缓存读写 ...
- 从零开始编写自己的C#框架(26)——小结
一直想写个总结,不过实在太忙了,所以一直拖啊拖啊,拖到现在,不过也好,有了这段时间的沉淀,发现自己又有了小小的进步.哈哈...... 原想框架开发的相关开发步骤.文档.代码.功能.部署等都简单的讲过了 ...
- Python自然语言处理工具小结
Python自然语言处理工具小结 作者:白宁超 2016年11月21日21:45:26 目录 [Python NLP]干货!详述Python NLTK下如何使用stanford NLP工具包(1) [ ...
- java单向加密算法小结(2)--MD5哈希算法
上一篇文章整理了Base64算法的相关知识,严格来说,Base64只能算是一种编码方式而非加密算法,这一篇要说的MD5,其实也不算是加密算法,而是一种哈希算法,即将目标文本转化为固定长度,不可逆的字符 ...
- 文件随机读写专用类——RandomAccessFile
RandomAccessFile类可以随机读取文件,但是在测试中并不好用;File类可以测试文件存不存在,不存在可以创建文件;FileWriter类可以对文件进行重写或者追加内容;FileReade ...
随机推荐
- cAdvisor0.24.1+InfluxDB0.13+Grafana4.0.2搭建Docker1.12.3 Swarm集群性能监控平台
目录 [TOC] 1.基本概念 既然是对Docker的容器进行监控,我们就不自己单独搭建cAdvisor.InfluxDB.Grarana了,本文中这三个实例,主要以Docker容器方式运行. 本 ...
- [2014.01.27]wfTextImage 文字图像组件 1.6
全新开发的文字转图像组件--wfTextImage,使用简单,功能强大,图像处理效果极佳. 将大段的文本内容转换成GIF图片. 有效防止文字内容被复制抄袭,有效保护文字资料. ...
- ios 写项目的时候遇到的问题及解决方案(2)
11.自适应文本高度 NSDictionary *attributes = @{NSFontAttributeName: [UIFont systemFontOfSize:]}; CGRect rec ...
- linux---mysql远程访问
1.远程连接上Linux系统,确保Linux系统已经安装上了MySQL数据库. 登陆数据库.mysql -uroot -p(密码). 2.创建用户用来远程连接 GRANT ALL PRIVILEGES ...
- 循环语句--for
1.guess_age优化版v1.py #coding=utf-8 age = 22 for i in range(10): if i < 3: guess_num = int(input('i ...
- 【总结】JS里的数组排序
虽然贴了2种办法,但是思路是一致的,都是先从数组里找出最小值,一种是找到一个放进新数组: 另一种是找到后和第i个数交换,i每次自增 主要用到2个函数: 从一个数组里找出最小值: 两个元素互换位置 fu ...
- phpinfo有mysqlnd没有mysql
这个着实是个坑,使用phpinfo查看,明明有mysqlnd这个项目,就是找不到mysql.以前用直接运行php.exe的方法可以看到错误,可是这次就没有任何错误. 中间把php的安装路径添加到了系统 ...
- [HDU 4336] Card Collector (状态压缩概率dp)
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4336 题目大意:有n种卡片,需要吃零食收集,打开零食,出现第i种卡片的概率是p[i],也有可能不出现卡 ...
- C#调用java类、jar包方法(转)
一.将已经编译后的java中Class文件进行打包:打包命令JAR 如:将某目录下的所有class文件夹全部进行打包处理: 使用的命令:jar cvf test.jar -C com/ . 其中tes ...
- Extjs 百度地图扩展
var bmapps; Bsprint.EditMapInfoWindow = Ext.extend(Ext.Window, { form: null, constructor: function ( ...