JavaSE-IO流(随机存储文件流RandomAccessFile)

1、RandomAccessFile概念

在这里插入图片描述
在这里插入图片描述在这里插入图片描述

2、RandomAccessFile实现数据的读写操作

public class RandomAccessFileTest {
    @Test
    public void test(){
        RandomAccessFile raf = null;
        RandomAccessFile raf1 = null;
        try {
            //1、
            raf = new RandomAccessFile(new File("bird.png"),"r");
            raf1 = new RandomAccessFile(new File("bird1.png"),"rw");
            //2、
            byte[] buffer = new byte[1024];
            int len;
            while((len=raf.read(buffer))!=-1){
                raf1.write(buffer,0,len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if(raf!=null){
                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if(raf1!=null){
                try {
                    raf1.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
//如果RandomAccessFile作为输出流时,写出到的文件hello.txt如果不存在,则执行过程中会自动创建;如果写出到的文件存在,则会对原有文件内容进行覆盖(从文件开头开始覆盖内容)。
@Test
public void test02() throws IOException {
   RandomAccessFile raf = new RandomAccessFile("hello.txt","rw");
   raf.write("xyz".getBytes());
   raf.close();
}

hello.txt文件已创建,内容如下。执行上述操作之前的hello.txt
在这里插入图片描述
执行上述操作之后的hello.txt。文件内容被从头覆盖
在这里插入图片描述

3、RandomAccessFile实现数据的插入操作

/**
 * 使用RandomAccessFile实现数据的插入操作
 */
@Test
public void test04() throws IOException {
    RandomAccessFile raf  = new RandomAccessFile("hello.txt","rw");

    raf.seek(3);//将指针调到角标为3的位置
    // 保存指针3后面的所有数据存到StringBuilder中
    StringBuilder builder = new StringBuilder((int) new File("hello.txt").length());
    byte[] buffer = new byte[20];
    int len;
    while((len=raf.read(buffer))!=-1){
        builder.append(new String(buffer,0,len));
    }
    //调回指针,写入“xyz"
    raf.seek(3);
    raf.write("xyz".getBytes());
    //将StringBuilder中的数据写入到文件中
    raf.write(builder.toString().getBytes());

    raf.close();
}

执行插入操作前的hello.txt文件
在这里插入图片描述执行插入操作后的hello.txt文件
在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值