1. 程式人生 > >java的兩種檔案拷貝方式

java的兩種檔案拷貝方式

一.基礎

三種IO方式

1.傳統IO方式,基於流模型實現,提供了File抽象,輸入輸出流等,互動方式是同步,阻塞的方式,也就是說在讀寫動作完成之前,執行緒一直阻塞在那裡。

2.NIO  引入了Channel,Selector,Buffer等新的抽象,可以構建多路複用的,同步非阻塞的IO程式

3.AIO  非同步非阻塞

 

二.實現

1.利用java.io.類庫,直接為原始檔構建一個FileInputStream讀取,然後再為目標檔案構建一個FileOutputStream,完成寫入工作

 

public  static  boolean  copyFile(String  source,String  dest){
    InputStream  inputStream = null;
    OutputStream outputStream = null;
    try {
        inputStream = new FileInputStream(source);
        outputStream = new FileOutputStream(dest);
        byte[]  buffer = new byte[1024];
        int bytesRead;
        while((bytesRead=inputStream.read(buffer))!=-1){
            outputStream.write(buffer, 0, bytesRead);
        }
        inputStream.close();
        outputStream.close();
    } catch (FileNotFoundException e) {
        logger.warn("fileUtil_copyFile_sourceFile",source,e);
        return false;
    } catch (IOException e) {
        logger.warn("fileUtil_copyFile_param{}_{}",source,dest,e);
        return false;
    }
    return true;
}

2.利用java.nio類庫提供的transferTo或transferFrom方式實現

public  static  boolean  copyFileNio(String  source,String  dest){
    FileInputStream  inputStream = null;
    FileOutputStream outputStream = null;
    try {
        inputStream = new FileInputStream(source);
        outputStream = new FileOutputStream(dest);
        FileChannel sourceCh = inputStream.getChannel();
        FileChannel destCh = outputStream.getChannel();
        destCh.transferFrom(sourceCh, 0, sourceCh.size());
        sourceCh.close();
        destCh.close();
    } catch (FileNotFoundException e) {
        logger.warn("fileUtil_copyFile_sourceFile",source,e);
        return false;
    } catch (IOException e) {
        logger.warn("fileUtil_copyFile_param{}_{}",source,dest,e);
        return false;
    }
    return true;
}

經過測試第二種方式要比第一種方式快很多

第一種方式:

     當使用輸入輸出流進行讀寫時,實際上進行了多次上下文切換,比如應用讀取資料時,先在核心態將資料從磁碟讀取到核心快取,在切換到使用者態將資料從核心快取讀取到使用者快取。

第二種方式:

    實現了零拷貝,資料傳輸並不需要使用者態參與,省去上下文切換的開銷和不必要的記憶體拷貝,進而可能提高應用拷貝效能。注意,transferTo 不僅僅是可以用在檔案拷貝中,與其類似的,例如讀取磁碟檔案,然後進行 Socket 傳送,同樣可以享受這種機制帶來的效能和擴充套件性提高。