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));
        }
    }
  • 相关阅读:
    NOIP2015 斗地主
    BZOJ 2120: 数颜色
    BZOJ 1014: [JSOI2008]火星人prefix
    BZOJ 4665: 小w的喜糖
    BZOJ 3665: maths
    BZOJ 3270: 博物馆
    BZOJ 1419: Red is good
    【转】二分图的最大匹配
    POJ 3026 Borg Maze(Prim+BFS建邻接矩阵)
    POJ 2485 Highway(Prim+邻接矩阵)
  • 原文地址:https://www.cnblogs.com/xiaozhang666/p/13224889.html
Copyright © 2011-2022 走看看