一、RandomAccessFile类
- 直接继承于java.lang.Object类,实现了DataInput和DataOutput接口
- 既可以作为输入流,也可以作为输出流
- 作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建文件
如果写出的文件存在,则会对原有文件内容进行从头覆盖(默认position指针位置为0,调用seek(int pos)
方法改变指针位置,则可以实现从指定位置开始覆盖)
构造器
RandomAccessFile(String pathname,String mode)
;
RandomAccessFile(File filename,String mode)
。- 参数
mode
:该参数指定RandomAccesFile的访问模式
r
:以只读方式打开
rw
:打开以便读取和写入
rwd
:打开以便读取和写入;同步文件内容的更新
rws
:打开以便读取和写入;同步文件内容的更新和元数据的更新
实现字节型文件的复制
@Test
public void testForRandomAccessFile(){
RandomAccessFile rafot = null;
RandomAccessFile rafin = null;
try {
//造流
//RandomAccessFile(String pathname,String mode)
rafot = new RandomAccessFile(new File("皮卡丘.jpg"),"r");
rafin = new RandomAccessFile(new File("皮卡丘副本.jpg"),"rw");
//操作
byte[] buffer = new byte[1024];
int len;
while ((len = rafot.read(buffer)) != -1){
rafin.write(buffer,0,len);
}
System.out.println(rafin.read());
} catch (IOException e) {
e.printStackTrace();
} finally {
if (rafot != null) {
try {
rafot.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (rafin != null) {
try {
rafin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
使用RandomAccessFile实现指定位置插入效果
@Test
public void test1() {
RandomAccessFile raf1 = null;
try {
raf1 = new RandomAccessFile(new File("hello.txt"), "rw");
raf1.seek(3);//将指针调到第4个字符
//保存指针3后面的所有数据到StringBuider中
StringBuilder builder = new StringBuilder((int) new File("hello.txt").length());
byte[] buffer = new byte[20];
int len;
while ((len = raf1.read(buffer)) != -1){
builder.append(new String(buffer,0,len));
}
//调用指针写入“xyz”
raf1.seek(3);//将指针调到第4个字符
raf1.write("xxxxxxx".getBytes());
//写入StringBuffer中存储的剩余字符串
raf1.write(builder.toString().getBytes());
} catch (IOException e) {
e.printStackTrace();
} finally {
if(raf1 != null){
try {
raf1.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//关闭流
}
运行前效果:
运行后效果: