博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
NIO(四)
阅读量:4698 次
发布时间:2019-06-09

本文共 2237 字,大约阅读时间需要 7 分钟。

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

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));    }}

 

转载于:https://www.cnblogs.com/jiefu/p/10041702.html

你可能感兴趣的文章
j.c.Warnsdorff马踏棋盘算法
查看>>
the openning
查看>>
python 字符串 和 print
查看>>
MAC OS下安装Minizip
查看>>
Java_Certificates does not conform to algorithm constraints
查看>>
PAT 1027. Colors in Mars
查看>>
linux定时执行脚本
查看>>
Oauth支持的5类 grant_type 及说明
查看>>
ASP.NET 5 DNX SDK删除旧版本
查看>>
Android ListView 九大重要属性详细分析
查看>>
CC++中sizeof函数的用法
查看>>
SPFA 算法详解( 强大图解,不会都难!) (转)
查看>>
QUIC:基于udp的传输新技术
查看>>
java常见面试题及部分答案
查看>>
动态添加方法的代码分析
查看>>
thinkPHP5.0使用模型新增数据
查看>>
客户端第一天学习的相关知识
查看>>
LeetCode - Same Tree
查看>>
Python dict get items pop update
查看>>
[置顶] 程序员必知(二):位图(bitmap)
查看>>