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

 

 

 

 

 

    

 

posted @ 2017-04-23 22:02  大师兄-  阅读(510)  评论(0编辑  收藏  举报