1. 程式人生 > >JAVA NIO(三) 三種檔案的複製方法與效率對比

JAVA NIO(三) 三種檔案的複製方法與效率對比

檔案的複製最能體現io效率了.因為既需要讀取資料還需要寫出到硬碟中,下面提供了三種檔案複製的方法 可以對比一下 直接緩衝區與非直接緩衝區的效率對比.

public class Nio {

    public static void main(String[] args) throws IOException {
        nioCopyTest1();
        nioCopyTest2();
        nioCopyTest3();
    }

    /**通道之間的資料傳輸(直接緩衝區的模式)
     *
     */
private static void   nioCopyTest3() throws 
IOException { long startTime = System.currentTimeMillis(); FileChannel inChannel = FileChannel.open(Paths.get("E:\\ 1.avi"), StandardOpenOption.READ); FileChannel outChennel = FileChannel.open(Paths.get("E:\\ 13.avi"),StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE_NEW
); outChennel.transferFrom(inChannel,0,inChannel.size()); long end = System.currentTimeMillis(); System.out.println("nioCopyTest3耗費時間:"+(end-startTime)); } /** * 使用直接緩衝區完成檔案的複製(記憶體對映檔案) */ private static void nioCopyTest2() throws IOException { long
startTime = System.currentTimeMillis(); FileChannel inChannel = FileChannel.open(Paths.get("E:\\ 1.avi"), StandardOpenOption.READ); FileChannel outChennel = FileChannel.open(Paths.get("E:\\ 12.avi"),StandardOpenOption.WRITE,StandardOpenOption.READ,StandardOpenOption.CREATE_NEW); //記憶體對映檔案(什麼模式 從哪開始 到哪結束) MappedByteBuffer inMappeBuf = inChannel.map(FileChannel.MapMode.READ_ONLY,0,inChannel.size()); MappedByteBuffer outMappeBuf = outChennel.map(FileChannel.MapMode.READ_WRITE,0,inChannel.size()); //直接都緩衝區進行資料的讀寫操作 byte[] dst = new byte[inMappeBuf.limit()]; inMappeBuf.get(dst); outMappeBuf.put(dst); inChannel.close(); outChennel.close(); long end = System.currentTimeMillis(); System.out.println("nioCopyTest2耗費時間:"+(end-startTime)); } /** * 非直接緩衝區 檔案的複製 * @throws IOException */ private static void nioCopyTest1()throws IOException { long startTime = System.currentTimeMillis(); FileInputStream fileInputStream = new FileInputStream(new File("E:\\ 1.avi")); FileOutputStream fileOutputStream = new FileOutputStream("E:\\ 11.avi"); //獲取通道 FileChannel inChannel = fileInputStream.getChannel(); FileChannel outChanel = fileOutputStream.getChannel(); //分配緩衝區的大小 ByteBuffer buf = ByteBuffer.allocate(1024); //將通道中的資料存入緩衝區 while (inChannel.read(buf) != -1) { buf.flip();//切換讀取資料的模式 outChanel.write(buf); buf.clear(); } outChanel.close(); inChannel.close(); fileInputStream.close(); fileOutputStream.close(); long end = System.currentTimeMillis(); System.out.println("nioCopyTest1耗費時間:"+(end-startTime)); } }


控制檯輸出:

nioCopyTest1耗費時間:1417
nioCopyTest2耗費時間:142

nioCopyTest3耗費時間:68

直接緩衝不需要檔案的複製拷貝 所以大大增加效率 其中第三種方法通道之間的檔案傳輸 速度最快了直接在通道中完成.