Fork me on GitHub

基于直接缓冲区和非直接缓冲区的javaIO文件操作

基本概念:

1. 非直接缓冲区:  指的是通过jvm来缓存数据的,应用程序要读取本地数据要经历从本地磁盘到物理内存,然后copy到jvm中,然后再通过流的方式读取到应用程序中,写的操作正好与之相反。

2. 直接缓冲区:指不通过应用程序读取磁盘的文件时不用经过jvm,而是直接由本地磁盘到物理内存,然后到应用程序。

对比:直接缓冲方式会比非直接缓冲方式快,不过在保存文件到本地过程中,文件先保存到物理内存,途中如果用清理内存工具来进行清理的话,数据就会丢失。因此非直接缓冲区的方式比较安全。

我们来看一下直接缓冲IO操作的代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
long statTime=System.currentTimeMillis();
        //创建管道
        FileChannel   inChannel=    FileChannel.open(Paths.get("D://test001.mp4"), StandardOpenOption.READ);
        FileChannel   outChannel=   FileChannel.open(Paths.get("D://test002.mp4"), StandardOpenOption.READ,StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        //定义映射文件
        MappedByteBuffer inMappedByte = inChannel.map(MapMode.READ_ONLY,0, inChannel.size());
        MappedByteBuffer outMappedByte = outChannel.map(MapMode.READ_WRITE,0, inChannel.size());
        //直接对缓冲区操作
        byte[] dsf=new byte[inMappedByte.limit()];
        inMappedByte.get(dsf);
        outMappedByte.put(dsf);
        inChannel.close();
        outChannel.close();
        long endTime=System.currentTimeMillis();
        System.out.println("操作直接缓冲区耗时时间:"+(endTime-statTime));

  再来对比一下非直接缓冲区IO操作的代码:

复制代码
                long statTime=System.currentTimeMillis();
        // 读入流
        FileInputStream fst = new FileInputStream("D://test001.mp4");
        // 写入流
        FileOutputStream fos = new FileOutputStream("D://test002.mp4");
        // 创建通道
        FileChannel inChannel = fst.getChannel();
        FileChannel outChannel = fos.getChannel();
        // 分配指定大小缓冲区
        ByteBuffer buf = ByteBuffer.allocate(1024);
        while (inChannel.read(buf) != -1) {
            // 开启读取模式
            buf.flip();
            // 将数据写入到通道中
            outChannel.write(buf);
            buf.clear();
        }
        // 关闭通道 、关闭连接
        inChannel.close();
        outChannel.close();
        fos.close();
        fst.close();
        long endTime=System.currentTimeMillis();
        System.out.println("操作非直接缓冲区耗时时间:"+(endTime-statTime));
复制代码

 

posted @   黄高林  阅读(488)  评论(0编辑  收藏  举报
编辑推荐:
· AI与.NET技术实操系列:基于图像分类模型对图像进行分类
· go语言实现终端里的倒计时
· 如何编写易于单元测试的代码
· 10年+ .NET Coder 心语,封装的思维:从隐藏、稳定开始理解其本质意义
· .NET Core 中如何实现缓存的预热?
阅读排行:
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 零经验选手,Compose 一天开发一款小游戏!
· 通过 API 将Deepseek响应流式内容输出到前端
· AI Agent开发,如何调用三方的API Function,是通过提示词来发起调用的吗
点击右上角即可分享
微信分享提示