NIO(五)
阿新 • • 發佈:2018-11-29
使用非直接緩衝區和直接緩衝區複製同一個檔案,看一下時間差別
1、建立非直接緩衝區測試類
package com.cppdy.nio; import java.io.FileInputStream; import java.io.FileOutputStream; import java.nio.ByteBuffer; import java.nio.channels.FileChannel; //使用非直接緩衝區和直接緩衝區複製同一個檔案,看一下時間差別 public class NIOBufferDemo3 { public static void main(String[] args) throwsException { long start = System.currentTimeMillis(); FileInputStream fis = new FileInputStream("F:\\cppdy\\1.mp4"); FileOutputStream fos = new FileOutputStream("F:\\cppdy\\2.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(); fos.close(); fis.close(); long end = System.currentTimeMillis(); System.out.println("使用非直接緩衝區複製完畢mp4,耗時:" + (end - start)); } }
2、建立直接緩衝區測試類
package com.cppdy.nio; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.channels.FileChannel.MapMode; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; //使用非直接緩衝區和直接緩衝區複製同一個檔案,看一下時間差別 public class NIOBufferDemo4 { public static void main(String[] args) throws Exception { long start = System.currentTimeMillis(); // 直接緩衝區 FileChannel inChannel = FileChannel.open(Paths.get("F:\\cppdy\\1.mp4"), StandardOpenOption.READ); FileChannel outChannel = FileChannel.open(Paths.get("F:\\cppdy\\2.mp4"), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE); // 緩衝區 MappedByteBuffer inMap = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size()); MappedByteBuffer outMap = outChannel.map(MapMode.READ_WRITE, 0, inChannel.size()); // 直接對緩衝區進行資料讀寫操作 byte[] bytes = new byte[inMap.limit()]; inMap.get(bytes); outMap.put(bytes); outMap.clear(); outChannel.close(); inChannel.close(); long end = System.currentTimeMillis(); System.out.println("使用直接緩衝區複製完畢mp4,耗時:" + (end - start)); } }