package com.nio; import java.io.IOException; import java.nio.MappedByteBuffer; import java.nio.channels.FileChannel; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.Map; import static java.nio.channels.FileChannel.*; import static java.nio.channels.FileChannel.MapMode.*; /** * 使用直接缓存区完成文件的复制(内存映射文件) 注意:只有bytebuffer支持内存映射文件 * 此种方式,小数据量不建议使用,系统初始化缓存区比较耗费时间,大数据量的时候可以使用 在进行大文件复制的时候,使用这种方式耗时比较短。 */ public class TestChannel2 { public static void main(String[] args) throws IOException { FileChannel inChannel = FileChannel.open(Paths.get("001.jpg"), StandardOpenOption.READ); FileChannel outChannel = FileChannel.open(Paths.get("002.jpg"), StandardOpenOption.WRITE,StandardOpenOption.READ, StandardOpenOption.CREATE); //内存映射文件 MappedByteBuffer inMappedBuf =inChannel.map(MapMode.READ_ONLY,0, inChannel.size()); MappedByteBuffer outMapperBuf = outChannel.map(MapMode.READ_WRITE, 0, inChannel.size()); //直接对缓存区进行数据的读写操作 byte[] dst = new byte[inMappedBuf.limit()]; inMappedBuf.get(dst); outMapperBuf.put(dst); //关闭通道 inChannel.close(); outChannel.close(); } }