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));
        }
    }
  • 相关阅读:
    Android之旅七 Service简介
    使用CALayer实现图像镜面效果
    hdu4587 TWO NODES
    js Ajax
    SQL Server 2008数据库备份与恢复
    11g R2单实例手工建库
    needtrue需要真实的答案
    字符编码,pyton中的encode,decode,unicode()
    用java源代码学数据结构<七>: BST
    SQL MIN() 函数
  • 原文地址:https://www.cnblogs.com/xiaozhang666/p/13224889.html
Copyright © 2011-2022 走看看