13_8、Java的IO流之随机存取文件流(RandomAccessFile)的使用

一、随机存取文件流:RandomAccessFile

二、使用说明

1、RandomAccessFile类直接继承于java.lang.Object类,并实现了DataInput接口和DataOutput接口。

2、既可以作为输入流,也可以作为输出流使用

3、RandomAccessFile作为输出流,如果要写入的文件不存在,那么在执行过程中自动创建,如果要写入的文件已存在,那么对已的文件的内容进行覆盖。(默认从头开始覆盖)。

4、使用RandomAccessFile类的相关操作,实现“插入”效果(如果内容很大,则比较耗内存。) seek(int pos)方法,改变指针位置。

三、典型代码

1、复制操作

    @Test
    public void test1(){
        RandomAccessFile raf1 = null;
        RandomAccessFile raf2 = null;
        try {
            //1.
            raf1 = new RandomAccessFile(new File("绿地.jpeg"),"r");
            raf2 = new RandomAccessFile(new File("绿地1.jpeg"),"rw");

            //2.
            byte[] buffer = new byte[10];
            int len;
            while((len = raf1.read(buffer)) != -1){
                raf2.write(buffer,0,len);
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            if(raf1 != null){
                //3.
                try {
                    raf1.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
            if(raf2 != null){
                try {
                    raf2.close();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                }
            }
        }
    }

2、使用RandomAccessFile实现插入效果

    /*
    使用RandomAccessFile实现插入效果
     */

    @Test
    public void tst3() throws IOException {
        RandomAccessFile raf1 = new RandomAccessFile(new File("hello.txt"),"rw");

        StringBuilder sbd = new StringBuilder((int) new File("hello.txt").length());

        raf1.seek(3);//将角标调到第三个位置
        byte[] buffer = new byte[20];
        int len;
        while((len = raf1.read(buffer)) != -1){
            sbd.append(new String(buffer,0,len));
        }
        raf1.seek(3);//将角标调到第三个位置
        raf1.write("xyz".getBytes());

        //将sbd保存的内容写入到hello.txt
        raf1.write(sbd.toString().getBytes());

        raf1.close();
    }

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值