zoukankan      html  css  js  c++  java
  • NIO(四)

    使用非直接缓冲区和直接缓冲区复制同一个文件,看一下时间差别

    1、创建非直接缓冲区测试类

    package com.cppdy.nio;
    
    import java.io.FileInputStream;
    import java.io.FileOutputStream;
    import java.nio.ByteBuffer;
    import java.nio.channels.FileChannel;
    
    //使用非直接缓冲区和直接缓冲区复制同一个文件,看一下时间差别
    public class NIOBufferDemo3 {
    
        public static void main(String[] args) throws Exception {
    
            long start = System.currentTimeMillis();
            FileInputStream fis = new FileInputStream("F:\cppdy\1.mp4");
            FileOutputStream fos = new FileOutputStream("F:\cppdy\2.mp4");
    
            FileChannel inChannel = fis.getChannel();
            FileChannel outChannel = fos.getChannel();
    
            ByteBuffer buf = ByteBuffer.allocate(1024);
            while (inChannel.read(buf) != -1) {
                buf.flip();
                outChannel.write(buf);
                buf.clear();
            }
    
            outChannel.close();
            inChannel.close();
            fos.close();
            fis.close();
    
            long end = System.currentTimeMillis();
            System.out.println("使用非直接缓冲区复制完毕mp4,耗时:" + (end - start));
    
        }
    
    }

    2、创建直接缓冲区测试类

    package com.cppdy.nio;
    
    import java.nio.MappedByteBuffer;
    import java.nio.channels.FileChannel;
    import java.nio.channels.FileChannel.MapMode;
    import java.nio.file.Paths;
    import java.nio.file.StandardOpenOption;
    
    //使用非直接缓冲区和直接缓冲区复制同一个文件,看一下时间差别
    public class NIOBufferDemo4 {
    
        public static void main(String[] args) throws Exception {
    
            long start = System.currentTimeMillis();
            // 直接缓冲区
            FileChannel inChannel = FileChannel.open(Paths.get("F:\cppdy\1.mp4"), StandardOpenOption.READ);
            FileChannel outChannel = FileChannel.open(Paths.get("F:\cppdy\2.mp4"), StandardOpenOption.READ,
                    StandardOpenOption.WRITE, StandardOpenOption.CREATE);
            // 缓冲区
            MappedByteBuffer inMap = inChannel.map(MapMode.READ_ONLY, 0, inChannel.size());
            MappedByteBuffer outMap = outChannel.map(MapMode.READ_WRITE, 0, inChannel.size());
    
            // 直接对缓冲区进行数据读写操作
            byte[] bytes = new byte[inMap.limit()];
    
            inMap.get(bytes);
            outMap.put(bytes);
            outMap.clear();
            outChannel.close();
            inChannel.close();
            long end = System.currentTimeMillis();
            System.out.println("使用直接缓冲区复制完毕mp4,耗时:" + (end - start));
        }
    
    }
  • 相关阅读:
    12月12日总结
    练习:请用索引取出下面list的指定元素:
    练习:小明身高1.75,体重80.5kg。请根据BMI公式(体重除以身高的平方)帮小明计算他的BMI指数,并根据BMI指数:
    练习:请利用循环依次对list中的每个名字打印出Hello, xxx!:
    练习:学员管理系统
    练习:请修改列表生成式,通过添加if语句保证列表生成式能正确地执行
    CF1067D Computer Game
    高等数学第三章
    CF755G PolandBall and Many Other Balls
    TS泛型工具
  • 原文地址:https://www.cnblogs.com/jiefu/p/10041702.html
Copyright © 2011-2022 走看看