Java NIO 利用通道完成文件复制(MappedByteBuffer)

相关学习网址:

import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.FileChannel.MapMode;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

import org.junit.Test;

@Test
public void test2() throws IOException{
long start = System.currentTimeMillis();

    FileChannel inChannel = FileChannel.open(Paths.get("1.mp4"), StandardOpenOption.READ);
    FileChannel outChannel = FileChannel.open(Paths.get("2.mp4"), StandardOpenOption.WRITE, StandardOpenOption.READ, StandardOpenOption.CREATE);

    //内存映射文件
    MappedByteBuffer inMappedBuf = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size());
    MappedByteBuffer outMappedBuf = outChannel.map(MapMode.READ_WRITE, 0, inChannel.size());

    //直接对缓冲区进行数据的读写操作
    byte[] dst = new byte[inMappedBuf.limit()];
    inMappedBuf.get(dst);
    outMappedBuf.put(dst);

    inChannel.close();
    outChannel.close();

    long end = System.currentTimeMillis();
    System.out.println("耗费时间为:" + (end - start));
}

猜你喜欢

转载自blog.51cto.com/11056727/2173580