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();
}
}
}