使用非直接缓冲区与直接缓冲区进行文件的复制(基于Channel)

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

   

         long start = System.currentTimeMillis();
FileInputStream fis = new FileInputStream("g:/29.mp4");
FileOutputStream fos = new FileOutputStream("g:/30.mp4");
//获取通道
FileChannel inChannel = fis.getChannel();
FileChannel outChannel = fos.getChannel();
//分配指定大小缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
//将通道中的数据存入缓冲区
while (inChannel.read(buf) != -1){
buf.flip();
//将缓冲区的数据写入到通道中
outChannel.write(buf);
buf.clear();//清空缓冲区
}
outChannel.close();
inChannel.close();
fis.close();
fos.close(); long end = System.currentTimeMillis();
System.out.println("消耗的时间为:" + (end - start));//

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

         

         long start = System.currentTimeMillis();
FileChannel inChannel = FileChannel.open(Paths.get("g:/29.mp4"), StandardOpenOption.READ);
FileChannel outChannel = FileChannel.open(Paths.get("g:/30.mp4"), StandardOpenOption.WRITE,StandardOpenOption.READ, StandardOpenOption.CREATE); //内存映射文件
MappedByteBuffer inMappedBuf = inChannel.map(FileChannel.MapMode.READ_ONLY,0,inChannel.size());
MappedByteBuffer outMappedBuf = outChannel.map(FileChannel.MapMode.READ_WRITE,0,inChannel.size()); //直接对缓冲区进行数据的读写操作
byte[] dst = new byte[inMappedBuf.limit()];
inMappedBuf.get(dst);
outMappedBuf.put(dst); inChannel.close();
outChannel.close(); long end = System.currentTimeMillis();
System.out.println("消耗的时间为:" + (end - start));//
上一篇:C# 中的as和is小结


下一篇:OneNote的配置