IO與NIO複製文件性能對比

IO方式:       

public static void main(String[] args){
    InputStream inputStream= null;
    OutputStream outputStream = null;

   try {
       // normal
       File originalFile = new File("F:\\SL.US.S09E07.mp4");
       System.out.println("origianlFile size : " + originalFile.length());
       inputStream = new BufferedInputStream(new FileInputStream(originalFile));
       outputStream = new BufferedOutputStream(new FileOutputStream("F:\\dest.mkv"));

       long startTime = System.currentTimeMillis();
       byte[] readNum = new byte[1024];
       int i;
       while ((i = inputStream.read(readNum)) != -1) {
           outputStream.write(readNum, 0, i);
           outputStream.flush();
       }
       System.out.println("copyFile use times: " + (System.currentTimeMillis() - startTime));
       outputStream.close();
       inputStream.close();
   }catch (Exception e) {
       System.out.println("fail message : " + e.getMessage());
   }finally {
       closeStream(outputStream, inputStream);
   }
}

public static void closeStream(OutputStream outputStream, InputStream inputStream) {
    try {
        if (outputStream != null) {
            outputStream.close();
        }
        if (inputStream != null) {
            inputStream.close();
        }
    }catch (Exception e) {
        System.out.println("close stream fail, error msg : " + e.getMessage());
    }
}

結果:

origianlFile size : 702365976
copyFile use times: 3258

再來看使用IO方式複製文件性能:

public static void main(String[] args) {

    try {

        RandomAccessFile originalFile = new RandomAccessFile("F:\\SL.US.S09E07.mp4", "r");
        RandomAccessFile destFile = new RandomAccessFile("F:\\dest.mp4", "rw");
        long startTime = System.currentTimeMillis();
        // 此處是拿到讀的管道
        FileChannel originalChannel = originalFile.getChannel();
        // 此處是拿到寫的管道
        FileChannel destChannel = destFile.getChannel();
        long length = originalFile.length();
        System.out.println("file size : " + length);
        originalChannel.transferTo(0, length, destChannel);

        originalChannel.close();
        destChannel.close();
        System.out.println("needs times : " + (System.currentTimeMillis() - startTime));
    } catch (Exception e) {
        System.out.println("fail message : " + e.getMessage());
    } 
}

結果:

file size : 702365976
needs times : 965

 

對比我們發現使用NIO方式進行文件複製操作是遠遠快於普通IO流複製方式的;

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章