• 使用非直接缓冲区与直接缓冲区进行文件的复制(基于Channel)


    一、利用通道完成文件的复制(非直接缓冲区)

       

     1         long start = System.currentTimeMillis();
     2         FileInputStream fis = new FileInputStream("g:/29.mp4");
     3         FileOutputStream fos = new FileOutputStream("g:/30.mp4");
     4         //获取通道
     5         FileChannel inChannel = fis.getChannel();
     6         FileChannel outChannel = fos.getChannel();
     7         //分配指定大小缓冲区
     8         ByteBuffer buf = ByteBuffer.allocate(1024);
     9         //将通道中的数据存入缓冲区
    10         while (inChannel.read(buf) != -1){
    11             buf.flip();
    12             //将缓冲区的数据写入到通道中
    13             outChannel.write(buf);
    14             buf.clear();//清空缓冲区
    15         }
    16         outChannel.close();
    17         inChannel.close();
    18         fis.close();
    19         fos.close();
    20 
    21         long end = System.currentTimeMillis();
    22         System.out.println("消耗的时间为:" + (end - start));//3231

    二 、使用直接缓冲区完成文件的复制(内存映射)

             

     1         long start = System.currentTimeMillis();
     2         FileChannel inChannel = FileChannel.open(Paths.get("g:/29.mp4"), StandardOpenOption.READ);
     3         FileChannel outChannel = FileChannel.open(Paths.get("g:/30.mp4"), StandardOpenOption.WRITE,StandardOpenOption.READ, StandardOpenOption.CREATE);
     4 
     6         //内存映射文件
     7         MappedByteBuffer inMappedBuf = inChannel.map(FileChannel.MapMode.READ_ONLY,0,inChannel.size());
     8         MappedByteBuffer outMappedBuf = outChannel.map(FileChannel.MapMode.READ_WRITE,0,inChannel.size());
     9 
    10         //直接对缓冲区进行数据的读写操作
    11         byte[] dst = new byte[inMappedBuf.limit()];
    12         inMappedBuf.get(dst);
    13         outMappedBuf.put(dst);
    14 
    15         inChannel.close();
    16         outChannel.close();
    17 
    18         long  end = System.currentTimeMillis();
    19         System.out.println("消耗的时间为:" + (end - start));//522

     

        

  • 相关阅读:
    Spring Boot实现发送邮件
    IDEA thymeleaf ${xxx.xxx}表达式报错,红色波浪线
    解决springboot——集成 mybatis遇到的问题:No MyBatis mapper was found in '[com.example.demo]' package...
    解决Intellij IDEA中Mybatis Mapper自动注入警告
    System.gc()和Runtime.gc()的区别
    Java中定时器相关实现的介绍与对比之:Timer和TimerTask
    markdown语法介绍
    Java VisualVM使用
    Linux系统负载查询
    Kafka高性能吞吐关键技术分析
  • 原文地址:https://www.cnblogs.com/zengjiqiang/p/6754314.html
Copyright © 2020-2023  润新知