天天看點

基于FileChannel實作高效大資料量檔案寫入

測試結果:

    500W資料 5000一寫,15秒寫入完成

import java.io.*;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public abstract class FileUtils {

	/**
	 * append寫入
	 * @param file 檔案路徑
	 * @param content 待寫入的檔案内容
	 * @param bufferSize 單次寫入緩沖區大小 預設4M 1024 * 1024 * 4
	 */
	public static void write(String file, String content, Integer bufferSize) {

		bufferSize = null == bufferSize ? 4194304 : bufferSize;
		ByteBuffer buf = ByteBuffer.allocate(bufferSize);
		FileChannel channel = null;
		try {
			File fileTemp = new File(file);
			File parent = fileTemp.getParentFile();
			if (!parent.exists()) parent.mkdirs();
			if (!fileTemp.exists()) fileTemp.createNewFile();

			// new FileOutputStream(file, append)  第二個參數為true表示追加寫入
			channel = new FileOutputStream(file, true).getChannel();

			buf.put(content.getBytes());
			buf.flip();   // 切換為讀模式

			while(buf.hasRemaining()) {
				channel.write(buf);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				channel.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
}