分佈式系統開發-——常用工具類內部使用細節——0001

NIO 實現的文件快速複製  

package com.cheri.io;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @author Aaron Du
 * @version V1.0
 * @date 2020/4/22 21:37
 **/
public class NIOExample {

    public static void fastCopy(String src, String dist) throws IOException {
        /* 獲得源文件的輸入字節流 */
        FileInputStream fin = new FileInputStream(src);
        /* 獲取輸入字節流的文件通道 */
        FileChannel fcin = fin.getChannel();
        /* 獲取目標文件的輸出字節流 */
        FileOutputStream fout = new FileOutputStream(dist);
        /* 獲取輸出字節流的文件通道 */
        FileChannel fcout = fout.getChannel();
        /* 爲緩衝區分配 1024 個字節 */
        ByteBuffer buffer = ByteBuffer.allocateDirect(1024);
        while (true) {
            /* 從輸入通道中讀取數據到緩衝區中 */
            int r = fcin.read(buffer);
            /* read() 返回 -1 表示 EOF */
            if (r == -1) { break; }
            /* 切換讀寫 */
            buffer.flip();
            /* 把緩衝區的內容寫入輸出文件中 */
            fcout.write(buffer);
            /* 清空緩衝區 */
            buffer.clear();
        }
    }
}

 

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