NIO(三)

使用直接缓冲区完成文件的复制(内存映射文件)

package com.cppdy.nio;

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;

//使用直接缓冲区完成文件的复制(内存映射文件)
public class NIOBufferDemo2 {

    public static void main(String[] args) throws Exception {

        //直接缓冲区
        FileChannel inChannel = FileChannel.open(Paths.get("F:\\cppdy\\1.jpg"), StandardOpenOption.READ);
        FileChannel outChannel = FileChannel.open(Paths.get("F:\\cppdy\\2.jpg"), StandardOpenOption.READ,StandardOpenOption.WRITE,StandardOpenOption.CREATE);
        //缓冲区
        MappedByteBuffer inMap = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size());
        MappedByteBuffer outMap = outChannel.map(MapMode.READ_WRITE, 0, inChannel.size());
    
        //直接对缓冲区进行数据读写操作
        byte[] bytes=new byte[inMap.limit()];
        
        inMap.get(bytes);
        outMap.put(bytes);
        outMap.clear();
        System.out.println("复制完毕");
    }

}

 

posted @ 2018-11-29 23:22  知识追求者  阅读(137)  评论(0编辑  收藏  举报