Java IO RandomAccessFile 类随机访问流的使用细节详解
1. RandomAccessFile
-
RandomAccessFile 类支持 “随机访问” 的方式,程序可以直接跳到文件的任意地方来读、写文件
① 支持只访问文件的部分内容
② 可以向已存在的文件后追加内容 -
RandomAccessFile 对象包含一个记录指针,用以标示当前读写处的位置。RandomAccessFile 类对象可以自由移动记录指针:
① long getFilePointer():获取文件记录指针的当前位置
② void seek(long pos):将文件记录指针定位到 pos 位置 -
构造器
① public RandomAccessFile(File file, String mode)
② public RandomAccessFile(String name, String mode) -
创建 RandomAccessFile 类实例需要指定一个 mode 参数,该参数指定 RandomAccessFile 的访问模式:
① r: 以只读方式打开
② rw:打开以便读取和写入
③ rwd:打开以便读取和写入;同步文件内容的更新
④ rws:打开以便读取和写入;同步文件内容和元数据的更新
2.demo
1.RandomAccessFile 实现读和写
//实际是实现覆盖的效果
@Test
public void test2() {
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(new File("hello1.txt"),"rw");
raf.seek(3);//将指针调到3的位置
raf.write("xy".getBytes());
} catch (IOException e) {
e.printStackTrace();
}finally {
if(raf != null) {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
//进行文件的读、写
@Test
public void test1() {
RandomAccessFile raf1 = null;
RandomAccessFile raf2 = null;
try {
raf1 = new RandomAccessFile(new File("hello.txt"),"r");
raf2 = new RandomAccessFile(new File("hello1.txt"),"rw");
byte [] b = new byte[20];
int len ;
while((len = raf1.read(b)) != -1) {
raf2.write(b, 0, len);
}
} catch (IOException e) {
e.printStackTrace();
}
if(raf2 != null) {
try {
raf2.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(raf1 != null){
try {
raf1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.RandomAccessFile 实现插入效果
- 实现demo文件hello.txt内容,第一个方法为
- 代码
//实现插入的效果:在d字符的后面插入“xy”
@Test
public void test3() {
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(new File("hello.txt"),"rw");
raf.seek(4);
String str = raf.readLine();
// long l = raf.getFilePointer();
// System.out.println(l);//17
raf.seek(4);
raf.write("xy".getBytes());
raf.write(str.getBytes());
} catch (IOException e) {
e.printStackTrace();
}finally {
if(raf != null) {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
2.RandomAccessFile 更为通用的插入实现
- holle.txt文件
- test4()写法能够对换行进行处理,效果更好,test3()的写法,会导致数据变化
- 代码
//相较于test3,更通用
@Test
public void test4() {
RandomAccessFile raf = null;
try {
raf = new RandomAccessFile(new File("hello.txt"),"rw");
raf.seek(4);
byte[] b = new byte[10];
int len;
StringBuffer sb = new StringBuffer();
while((len = raf.read(b)) != -1) {
sb.append(new String(b,0,len));
}
raf.seek(4);
raf.write("xy".getBytes());
raf.write(sb.toString().getBytes());
} catch (IOException e) {
e.printStackTrace();
}finally {
if(raf != null) {
try {
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}