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("复制完毕");
    }

}

猜你喜欢

转载自www.cnblogs.com/cppdy/p/10041693.html
NIO