Java-------随机存取文件流

RandomAccessFile的使用
1.RandomAccessFile直接继承于java.lang.Object类,实现了DataInput和DataOutput接口
2.RandomAccessFile既可以作为一个输入流,又可以作为一个输出流
3.如果RandomAccessFile作为输出流时,写出到的文件如果不存在,则在执行过程中自动创建;如果写出到的文件存在,则会对原有文件内容进行覆盖。(默认情况下,从头覆盖)
4.可以通过相关的操作,实现RandomAccessFile“插入”数据的效果

    @Test
   public void test1() {

       RandomAccessFile raf1 = null;
       RandomAccessFile raf2 = null;
       try {
           raf1 = new RandomAccessFile(new File("壁纸.jpg"), "r");
           raf2 = new RandomAccessFile(new File("壁纸1.jpg"), "rw");

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

           if(raf1 != null){
               try {
                   raf1.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
       }

   }

    @Test
   public void test2() throws IOException {

       RandomAccessFile raf1 = new RandomAccessFile("hello.txt","rw");

       raf1.seek(3);//将指针调到角标为3的位置
       raf1.write("xyz".getBytes());

       raf1.close();

   }

使用RandomAccessFile实现数据的插入效果

    @Test
   public void test3() throws IOException {

       RandomAccessFile raf1 = new RandomAccessFile("hello.txt","rw");

       raf1.seek(3);
       //保存指针3后面的所有数据到StringBuilder中
       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);
       raf1.write("xyz".getBytes());

       //将StringBuilder中的数据写入到文件中
       raf1.write(builder.toString().getBytes());

       raf1.close();

   }
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值