前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >直接缓冲区操作示例

直接缓冲区操作示例

作者头像
Dream城堡
发布2022-01-07 17:23:14
2130
发布2022-01-07 17:23:14
举报
文章被收录于专栏:Spring相关Spring相关
代码语言:javascript
复制
public class FeiZhiJieHeZhiJie {


    /**
     * 非直接缓冲区写入操作
     */
    @Test
    public void test001() throws Exception {

        FileChannel inChannel = null;
        FileChannel outChannel = null;
        FileInputStream fis = null;
        FileOutputStream fos = null;

        try {
            long startTime = System.currentTimeMillis();

            // 读入流
            fis = new FileInputStream(String.valueOf(Paths.get("1024.jpg")));
            // 写入流
            fos = new FileOutputStream("1025.jpg");
            // 创建通道
            inChannel = fis.getChannel();
            outChannel = fos.getChannel();

            // 分配指定大小缓冲区
            ByteBuffer byteBuffer = ByteBuffer.allocate(1024);

            while (inChannel.read(byteBuffer) != -1) {
                // 开启读取模式
                byteBuffer.flip();
                // 将数据写入到通道中
                outChannel.write(byteBuffer);
                byteBuffer.clear();
            }

            System.out.println("非直接缓冲区耗时:"+(System.currentTimeMillis()-startTime));

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (inChannel != null) {
                // 关闭通道
                inChannel.close();
            }
            if (outChannel != null) {
                outChannel.close();
            }
            if (fis != null) {
                fis.close();
            }
            if (fos != null) {
                fos.close();
            }
        }


    }


    /**
     * 直接缓冲区
     *
     * @throws Exception
     */
    @Test
    public void test002() throws Exception {

        long startTime = System.currentTimeMillis();

        // 创建管道
        FileChannel inChannel = FileChannel.open(Paths.get("1024.jpg"), StandardOpenOption.READ);
        FileChannel outChannel = FileChannel.open(Paths.get("1025.jpg"),StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);

        // 定义映射文件
        MappedByteBuffer inputMbf = inChannel.map(FileChannel.MapMode.READ_ONLY, 0, inChannel.size());
        MappedByteBuffer outputMbf = outChannel.map(FileChannel.MapMode.READ_WRITE, 0, inChannel.size());

        // 直接对缓冲区进行操作
        byte[] dsf = new byte[inputMbf.limit()];
        inputMbf.get(dsf);
        outputMbf.put(dsf);
        inChannel.close();
        outChannel.close();
        System.out.println("操作直接缓冲区完毕");
        System.out.println("直接缓冲区耗时:"+(System.currentTimeMillis()-startTime));

    }


}
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2020-02-11 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档