使用非直接缓冲区与直接缓冲区进行文件的复制(基于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

 

 

 

 

 

    

 

转载于:https://www.cnblogs.com/zengjiqiang/p/6754314.html

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值