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));
        }
    }
  • 相关阅读:
    关于闭包和作用域的问题
    中文字体@font-face的导入
    一个跑马灯插件(持续优化)
    关于JS的clone()函数编写的一些问题
    函数的自执行,变量提升和函数提升
    Android 之Map容器替换 SparseArray,ArrayMap,ArraySet
    Anndroid GC 那些事
    Spark Streaming实时计算
    REDIS基础要点
    zookeeper要点总结
  • 原文地址:https://www.cnblogs.com/xiaozhang666/p/13224889.html
Copyright © 2011-2022 走看看