本文是基于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使用小结的更多相关文章

  1. JAVA(三)JAVA常用类库/JAVA IO

    成鹏致远 | lcw.cnblog.com |2014-02-01 JAVA常用类库 1.StringBuffer StringBuffer是使用缓冲区的,本身也是操作字符串的,但是与String类不 ...

  2. Java之RandomAccessFile小结

    今天跟大家分享一下javase中的关于I/O的操作: 有时我们需要在文件的末尾追加一些内容,在这时用RandomAccessFile就很好. 这个类有两个构造方法: RandomAccessFile( ...

  3. 通过扩展RandomAccessFile类使之具备Buffer改善I/O性能--转载

    主体: 目前最流行的J2SDK版本是1.3系列.使用该版本的开发人员需文件随机存取,就得使用RandomAccessFile类.其I/O性能较之其它常用开发语言的同类性能差距甚远,严重影响程序的运行效 ...

  4. RandomAccessFile类——高效快捷地读写文件

    RandomAceessFile类 RandomAccessFile类是一个专门读写文件的类,封装了基本的IO流,在读写文件内容方面比常规IO流更方便.更灵活.但也仅限于读写文件,无法像IO流一样,可 ...

  5. 在对文件进行随机读写,RandomAccessFile类,如何提高其效率

    花1K内存实现高效I/O的RandomAccessFile类 JAVA的文件随机存取类(RandomAccessFile)的I/O效率较低.通过分析其中原因,提出解决方案.逐步展示如何创建具备缓存读写 ...

  6. 从零开始编写自己的C#框架(26)——小结

    一直想写个总结,不过实在太忙了,所以一直拖啊拖啊,拖到现在,不过也好,有了这段时间的沉淀,发现自己又有了小小的进步.哈哈...... 原想框架开发的相关开发步骤.文档.代码.功能.部署等都简单的讲过了 ...

  7. Python自然语言处理工具小结

    Python自然语言处理工具小结 作者:白宁超 2016年11月21日21:45:26 目录 [Python NLP]干货!详述Python NLTK下如何使用stanford NLP工具包(1) [ ...

  8. java单向加密算法小结(2)--MD5哈希算法

    上一篇文章整理了Base64算法的相关知识,严格来说,Base64只能算是一种编码方式而非加密算法,这一篇要说的MD5,其实也不算是加密算法,而是一种哈希算法,即将目标文本转化为固定长度,不可逆的字符 ...

  9. 文件随机读写专用类——RandomAccessFile

     RandomAccessFile类可以随机读取文件,但是在测试中并不好用;File类可以测试文件存不存在,不存在可以创建文件;FileWriter类可以对文件进行重写或者追加内容;FileReade ...

随机推荐

  1. unity, 只发射一个粒子的粒子系统

  2. 首页使用page类完成生成页面内容的大部分工作

    fs2在处理异常及资源使用安全方面也有比较大的改善.fs2 Stream可以有几种方式自行引发异常:直接以函数式方式用fail来引发异常.在纯代码里隐式引发异常或者在运算中引发异常,最开始只是我自己浏 ...

  3. Windows Redis使用

    一.Redis 的安装 1.Redis 下载 Windows 版本下载:https://github.com/dmajkic/redis/downloads 2.解压到 C:\redis-2.4.5- ...

  4. Memcached 数据缓存系统

    Memcached 数据缓存系统 常用命令及使用:http://www.cnblogs.com/wayne173/p/5652034.html Memcached是一个自由开源的,高性能,分布式内存对 ...

  5. Maven间接依赖冲突解决办法

    如果项目中maven依赖太多,由于还有jar之间的间接依赖,所以可能会存在依赖冲突.依赖冲突大部分都是由于版本冲突引起的,查看maven的依赖关系,可以找到引起冲突的间接依赖 如上图,通过Depend ...

  6. SQL:实现流水账的收入、支出、本期余额

    有多组数据,分别是收入,支出,余额,它们的关系是:本期余额=上次余额+收入-支出 /* 测试数据: Create Table tbl([日期] smalldatetime,[收入] int ,[支出] ...

  7. js,addEventListener参数传递

    解决方法 因为i相对匿名函数是外面的变量,就把循环绑定的时候,将i的值传入到匿名函数内,就可以了.因此需要在匿名函数(事件函数)外包裹一个匿名函数, 并立即执行. var elems = docume ...

  8. mac版微信web开发者工具(小程序开发工具)无法显示二维码 解决方案

    微信小程序概念的提出,绝对可以算得上中国IT界惊天动地的一件大事,这可能意味着一场新的开发热潮即将到来, 我也怀着激动的心情准备全身心投入其中,不过截止目前,在官方网站上下载的最新版本都无法使用,打开 ...

  9. Oracle 11g服务器安装详细步骤

    原出处:http://jingyan.baidu.com/article/363872eccfb9266e4aa16f5d.html 方法/步骤   1 大家可以根据自己的操作系统是多少位(32位或6 ...

  10. [转]Django与遗留系统和数据库集成

    From:http://www.czug.org/python/django/17.html 尽管Django最适合从零开始开发项目--所谓的"绿色领域"开发--将框架与遗留系统和 ...