IO文件復制的三種方法


FileChannel實現文件復制
// 1、當文件大小小於2GB時,這種方式沒有什么大問題,但是如果文件小大超過2GB,這種方式就會數據丟失
// 測試文件大小:8832KB
public static void ioOption() throws IOException {
 
    // 文件輸入流通道
    FileChannel inputChannel = new FileInputStream(new File("D:/demo.txt")).getChannel();
    // 文件輸出流通道
    FileChannel outputChannel = new FileOutputStream(new File("D:/copy.txt")).getChannel();
    // 數據轉移
    inputChannel.transferTo(0, inputChannel.size(), outputChannel);
 
    inputChannel.close();
    outputChannel.close();
}
輸出:
耗時(毫秒):10
 
// 2、當文件大小超過2GB時處理辦法
// 測試文件大小:8832KB
public static void ioOption() throws IOException {
 
    // 文件輸入流通道
    FileChannel inputChannel = new FileInputStream(new File("D:/demo.txt")).getChannel();
    // 文件輸出流通道
    FileChannel outputChannel = new FileOutputStream(new File("D:/copy.txt")).getChannel();
 
    // 文件轉移起始位置,默認0
    long position  = 0;
    // 文件長度
    long size  = inputChannel.size();
    // 數據轉移
    // count 轉移的字節數
    long count = inputChannel.transferTo(position, size, outputChannel);
    // 循環方式,轉移數據
    // 比如:
    // 文件長度為220,但是一次只能轉移100;position = 0,size = 220
    // 100 < 220,
    // 第二次從100開始,轉移長度為120;position = 100,size = 120
    // 100 < 120,
    // 第三次從200開始,轉移長度為20;position = 200,size = 20
    // 20 = 20
    // 退出循環,轉移完畢
    while(count < size){
        position += count;
        size -= count;
        count = inputChannel.transferTo(position, size, outputChannel);
    }
 
    inputChannel.close();
    outputChannel.close();
}
傳統IO方式文件復制
3.
// 測試文件大小:8832KB
public static void ioOption4() throws IOException {
 
    // 獲取文件 字節輸入流,如果文件不存在拋出異常
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(new File("D:/demo.txt")));
    // 獲取文件 字節輸出流,如果文件不存在自動創建文件
    BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("D:/copy.txt")));
    // 字節數組
    byte[] bytes = new byte[1024];
 
    int len = 0;
    // 一次讀取一個 bytes 大小的數據
    // len 表示讀取到的字節數,如果沒有數據則返回 -1
    while ((len = bis.read(bytes))!= -1){
        bos.write(bytes,0,len);
    }
 
    bis.close();
    bos.close();
}
輸出:
耗時(毫秒):22

面向通道緩存的效率是面向流的的兩倍


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM