• 创建直接缓存区完成文件的复制


    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();
    
        }
    }
    

      

  • 相关阅读:
    [12.19模拟赛]矩形|扫描线+set
    网 络
    数组(二维)
    数组
    02-线程的三种创建方式
    01-线程(概念篇)
    IO流-文件操作
    Serializable 可串行化接口
    PrintStream 类
    ObjectIntputStream / ObjectOutputStream 类
  • 原文地址:https://www.cnblogs.com/dongyaotou/p/14414203.html
Copyright © 2020-2023  润新知