zoukankan      html  css  js  c++  java
  • 使用非直接缓冲区与直接缓冲区进行文件的复制(基于Channel)

    一、利用通道完成文件的复制(非直接缓冲区)

       

     1         long start = System.currentTimeMillis();
     2         FileInputStream fis = new FileInputStream("g:/29.mp4");
     3         FileOutputStream fos = new FileOutputStream("g:/30.mp4");
     4         //获取通道
     5         FileChannel inChannel = fis.getChannel();
     6         FileChannel outChannel = fos.getChannel();
     7         //分配指定大小缓冲区
     8         ByteBuffer buf = ByteBuffer.allocate(1024);
     9         //将通道中的数据存入缓冲区
    10         while (inChannel.read(buf) != -1){
    11             buf.flip();
    12             //将缓冲区的数据写入到通道中
    13             outChannel.write(buf);
    14             buf.clear();//清空缓冲区
    15         }
    16         outChannel.close();
    17         inChannel.close();
    18         fis.close();
    19         fos.close();
    20 
    21         long end = System.currentTimeMillis();
    22         System.out.println("消耗的时间为:" + (end - start));//3231

    二 、使用直接缓冲区完成文件的复制(内存映射)

             

     1         long start = System.currentTimeMillis();
     2         FileChannel inChannel = FileChannel.open(Paths.get("g:/29.mp4"), StandardOpenOption.READ);
     3         FileChannel outChannel = FileChannel.open(Paths.get("g:/30.mp4"), StandardOpenOption.WRITE,StandardOpenOption.READ, StandardOpenOption.CREATE);
     4 
     6         //内存映射文件
     7         MappedByteBuffer inMappedBuf = inChannel.map(FileChannel.MapMode.READ_ONLY,0,inChannel.size());
     8         MappedByteBuffer outMappedBuf = outChannel.map(FileChannel.MapMode.READ_WRITE,0,inChannel.size());
     9 
    10         //直接对缓冲区进行数据的读写操作
    11         byte[] dst = new byte[inMappedBuf.limit()];
    12         inMappedBuf.get(dst);
    13         outMappedBuf.put(dst);
    14 
    15         inChannel.close();
    16         outChannel.close();
    17 
    18         long  end = System.currentTimeMillis();
    19         System.out.println("消耗的时间为:" + (end - start));//522

     

        

  • 相关阅读:
    oracle 闪回操作--区别于快照
    easyui 低版本下拉多选框绑定onChange事件样式失真问题
    kvm虚拟机网络配置-网桥
    CentOS7.5使用KVM创建虚拟机
    梦醒时分
    姑娘
    Ventoy+WePE 装机教程
    PG-SSL安全配置
    转载-如何做一份完善的补丁分析
    网络流24题部分题解
  • 原文地址:https://www.cnblogs.com/zengjiqiang/p/6754314.html
Copyright © 2011-2022 走看看