Java使用文件通道复制文件

两种文件通道复制文件方式的性能比较

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

import org.junit.Test;

/**
 * 比较IO操作的性能比较
 * 1.内存映射最快
 * 2.NIO读写文件
 * 3.加了缓存流的IO
 * 4.普通IO
 * 使用文件通道的方式复制文件
 */
public class ChannelDemo {

	public static void main(String[] args) throws Exception {
		String src = "F:/022_37分钟零基础开发桌球小游戏项目~1.mp4";// 文件源路径,测试文件大小为145828字节
		String dest = "F:/022_37分钟零基础开发桌球小游戏项目~1bak.mp4";// 文件目的地路径

		copyFile(src, dest);// 总耗时:5457ms
		randomAccessFileCopy(src, dest);// 总耗时:1135ms
	}

	@Test
	private static void randomAccessFileCopy(String src, String dest) throws IOException {
		long start = System.currentTimeMillis();

		// 获得输入输出流的文件通道
		FileChannel fcIn = new RandomAccessFile(src, "r").getChannel();
		FileChannel fcOut = new RandomAccessFile(dest, "rw").getChannel();

		// 输入流的字节大小
		long size = fcIn.size();

		// 输入输出流映射到缓冲区
		MappedByteBuffer inBuf = fcIn.map(MapMode.READ_ONLY, 0, size);
		MappedByteBuffer outBuf = fcOut.map(MapMode.READ_WRITE, 0, size);

		// 目的:将输入流缓冲区的内容写到输出流缓冲区就完成了文件的复制
		// 操作的是缓冲区
		for (int i = 0; i < size; i++) {
			outBuf.put(inBuf.get());
		}

		// 关闭(关闭通道时会写入数据块)
		fcIn.close();
		fcOut.close();
		System.out.println("复制成功");

		long end = System.currentTimeMillis();
		System.out.println("总耗时:" + (end - start) + "ms");
	}

	@Test
	private static void copyFile(String src, String dest) throws Exception {

		long start = System.currentTimeMillis();

		// 获得输入流输出流的文件通道
		FileChannel fcIn = new FileInputStream(src).getChannel();
		FileChannel fcOut = new FileOutputStream(dest).getChannel();

		// 申请缓冲空间为1024个字节
		ByteBuffer buf = ByteBuffer.allocate(1024);
		while (fcIn.read(buf) != -1) {
			buf.flip();
			fcOut.write(buf);
			//清除缓存
			buf.clear();
		}

		//关闭通道
		fcIn.close();
		fcOut.close();
		System.out.println("复制成功");

		long end = System.currentTimeMillis();
		System.out.println("总耗时:" + (end - start) + "ms");
	}

}

比较IO操作的性能比较

  1. 内存映射最快
  2. NIO读写文件
  3. 加了缓存流的IO
  4. 普通IO(不加缓存流)
原文地址:https://www.cnblogs.com/zxfei/p/10961413.html