zoukankan      html  css  js  c++  java
  • 其他高效拷贝文件方式Channel和MappedByteBuffer

    Channel: 它是一个可以读写数据的通道,相当于IO流,但是与IO流有所不同,通道不区分输入和输出(是双向的)

    channel的分类:

      FileChannel 文件通道(用于读写文件)
      SocketChannel TCP协议客户端通道
      ServerSocketChannel TCP协议服务器通道

    FileChannel类的基本使用
    public class ByteBufferCopy {
        public static void main(String[] args) throws Exception {
            FileInputStream fileInputStream = new FileInputStream("111.txt");
            FileOutputStream fileOutputStream = new FileOutputStream("copt.txt");
    
            //获取ByteBuffer
            FileChannel ichannel = fileInputStream.getChannel();
            FileChannel ochannel = fileOutputStream.getChannel();
            //创建Channl
            ByteBuffer allocate = ByteBuffer.allocate(1024);
            int len = 0;
            while ((len = ichannel.read(allocate)) != -1) {
                allocate.flip();
                ochannel.write(allocate);
                allocate.clear();
            }
        }
    }
    FileChannel结合MappedByteBuffer实现高效读写
    public class RandomAccessFiles {
        public static void main(String[] args) throws Exception {
            RandomAccessFile irandomAccessFile = new RandomAccessFile("111.txt", "r");
            RandomAccessFile orandomAccessFile = new RandomAccessFile("copt222.txt", "rw");
            FileChannel ichannel = irandomAccessFile.getChannel();
            FileChannel ochannel = orandomAccessFile.getChannel();
            //
            long size = ichannel.size();
            MappedByteBuffer inMap = ichannel.map(FileChannel.MapMode.READ_ONLY,0,size);
            MappedByteBuffer outMap = ochannel.map(FileChannel.MapMode.READ_WRITE, 0, size);
            //4.复制
            long start = System.currentTimeMillis();
            for (int i = 0; i < size; i++) {
                byte b = inMap.get(i);
                outMap.put(i,b);
            }
            long end = System.currentTimeMillis();
            System.out.println("耗时:" + (end - start));
        }
    }
  • 相关阅读:
    linux常用命令总结
    python3使用465端口发送邮件来解决阿里云封闭25端口问题
    Bamboo Django Celery定时任务和时间设置
    优秀的web端 vue框架
    将HTML5 Canvas的内容保存为图片借助toDataURL实现
    .naturalWidth 和naturalHeight属性,
    HTML5之FileReader的使用
    详解 Array.prototype.slice.call(arguments)
    在页面关闭或者刷新的时候触发 onbeforeunload
    缓存图片
  • 原文地址:https://www.cnblogs.com/xiaozhang666/p/13224889.html
Copyright © 2011-2022 走看看