IO流-实现RandomAccessFile“插入”数据的操作

如题


    /*
    实现RandomAccessFile“插入”数据的操作
     */
    @Test
    public void test02(){
        RandomAccessFile raf = null;
        try {
            //1.
            raf = new RandomAccessFile("Hello.txt","rw");
            //2.
            //2.1将指针调到角标为3的位置
            raf.seek(3);

            //2.2保存3 以后的所有数据到builder中 最后再插入
            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());


            System.out.println("插入成功!");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            //3.
            if (raf!=null){

                try {
                    raf.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }

@Test是使用了Junit单元测试   大概就是一个不用main方法就可以运行的程序段

插入前:

插入后: 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值