java压缩文件工具类

2023-10-27

java压缩文件的各种方式及速度对比

1使用场景

开发过程中可能会用到压缩文件的需求,是用什么方式更快呢?本次就对几种常见的压缩方式做一个对比

2 maven依赖

引用commons-lang3的工具包

<dependency>
	<groupId>org.apache.commons</groupId>
	<artifactId>commons-lang3</artifactId>
	<version>3.9</version>
</dependency>

3 压缩文件工具类

话不多说 直接上代码

import org.apache.commons.lang3.time.StopWatch;
import java.io.*;
import java.nio.ByteBuffer;
import java.nio.MappedByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.Pipe;
import java.nio.channels.WritableByteChannel;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;


public class IOStreamTurningExample {

    public IOStreamTurningExample() {
    }

    /**

     Native IO Stream

     @param srcFile

     @param destFile
     */
    public static void nativeStreamWriterFile(File srcFile, File destFile) {

        final StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(destFile))) {
            try (final FileInputStream fileInputStream = new FileInputStream(srcFile)) {
                zipOutputStream.putNextEntry(new ZipEntry(destFile.getName()));
                byte[] b = new byte[1024 * 1024 * 5];
                int readSize = 0;
                while ((readSize = fileInputStream.read(b)) > 0) {
                    zipOutputStream.write(b, 0, readSize);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        stopWatch.stop();
        printInfo("nativeStreamWriterFile", stopWatch);
    }

    /**

     Use Buffer IO Stream

     @param srcFile

     @param destFile
     */
    public static void bufferStreamWriterFile(File srcFile, File destFile) {
        final StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(destFile));
             final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(zipOutputStream)) {

            try (final BufferedInputStream bufferedInputStream = new BufferedInputStream(new FileInputStream(srcFile))) {
                zipOutputStream.putNextEntry(new ZipEntry(destFile.getName()));
                byte[] b = new byte[1024 * 1024 * 5];
                int readSize = 0;
                while ((readSize = bufferedInputStream.read(b)) != -1) {
                    bufferedOutputStream.write(b, 0, readSize);
                }
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        stopWatch.stop();
        printInfo("bufferStreamWriterFile", stopWatch);
    }

    /**

     Use Channel IO Stream

     @param srcFile

     @param destFile
     */
    public static void channelStreamWriterFile(File srcFile, File destFile) {

        final long fileSize = srcFile.length();

        final StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(destFile));
             final WritableByteChannel writableByteChannel = Channels.newChannel(zipOutputStream)) {

            try (final FileChannel fileChannel = new FileInputStream(srcFile).getChannel()) {
                zipOutputStream.putNextEntry(new ZipEntry(destFile.getName()));

                fileChannel.transferTo(0, fileSize, writableByteChannel);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        stopWatch.stop();
        printInfo("channelStreamWriterFile", stopWatch);
    }

    /**

     @param srcFile

     @param destFile
     */
    public static void mappedStreamWriterFile(File srcFile, File destFile) {
        final long fileSize = srcFile.length();

        final StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        try (ZipOutputStream zipOutputStream = new ZipOutputStream(new FileOutputStream(destFile));
             final WritableByteChannel writableByteChannel = Channels.newChannel(zipOutputStream)) {

            zipOutputStream.putNextEntry(new ZipEntry(destFile.getName()));

            try (final FileChannel fileChannel = new RandomAccessFile(srcFile, "r").getChannel()) {
                final MappedByteBuffer mappedByteBuffer = fileChannel.map(FileChannel.MapMode.READ_ONLY, 0, fileSize);
                writableByteChannel.write(mappedByteBuffer);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        stopWatch.stop();
        printInfo("mappedStreamWriterFile", stopWatch);
    }

    /**
     *
     */
    public static void pipeStreamWriterFile(File srcFile, File destFile) {
        final long fileSize = srcFile.length();

        final StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        try (ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(destFile));
             final WritableByteChannel writableByteChannel = Channels.newChannel(zos)) {

            zos.putNextEntry(new ZipEntry(destFile.getName()));

            final Pipe pipe = Pipe.open();

            CompletableFuture.runAsync(() -> {
                try (ZipOutputStream zipOutputStream1 = new ZipOutputStream(Channels.newOutputStream(pipe.sink()));
                     final WritableByteChannel writableByteChannel1 = Channels.newChannel(zipOutputStream1)) {

                    zipOutputStream1.putNextEntry(new ZipEntry(destFile.getName()));

                    final FileChannel destFileChannel = new FileInputStream(srcFile).getChannel();
                    destFileChannel.transferTo(0, fileSize, writableByteChannel1);
                    destFileChannel.close();
                } catch (FileNotFoundException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            });

            final Pipe.SourceChannel sourceChannel = pipe.source();
            final ByteBuffer buffer = ByteBuffer.allocate(1024 * 1024 * 10);

            while (sourceChannel.read(buffer) >= 0) {
                buffer.flip();
                writableByteChannel.write(buffer);
                buffer.clear();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        stopWatch.stop();
        printInfo("pipeStreamWriterFile", stopWatch);
    }

    private static void printInfo(String method, StopWatch stopWatch) {

        System.out.println("\n\n" + method + ":");
        System.out.println("Start Time : " + stopWatch.getStartTime());
        System.out.println("Duration Time : " + stopWatch.toString());
    }

    public static void main(String[] args) {

        File src_file = new File("D:/test/haha.mp4");

        File dest_file = new File("D:/test/haha.mp4");


        nativeStreamWriterFile(src_file, dest_file);

        bufferStreamWriterFile(src_file, dest_file);

        channelStreamWriterFile(src_file, dest_file);

        mappedStreamWriterFile(src_file, dest_file);

        pipeStreamWriterFile(src_file, dest_file);

        try {
            TimeUnit.SECONDS.sleep(100);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

复制代码修改main方法中的测试文件地址执行并直接执行

4 对比结果查看

haha.mp4是一个1.13G的视频文件
各种方式压缩对比结果:

nativeStreamWriterFile:
Start Time : 1573884268436
Duration Time : 0:00:52.334

bufferStreamWriterFile:
Start Time : 1573884320778
Duration Time : 0:00:51.496

channelStreamWriterFile:
Start Time : 1573884372275
Duration Time : 0:00:52.157

mappedStreamWriterFile:
Start Time : 1573884424432
Duration Time : 0:00:51.618

pipeStreamWriterFile:
Start Time : 1573884476051
Duration Time : 0:01:19.865
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

java压缩文件工具类 的相关文章

随机推荐

  • Dockerfile命令详解之 RUN(二):RUN --mount=type=bind

    许多同学不知道Dockerfile应该如何写 不清楚Dockerfile中的指令分别有什么意义 能达到什么样的目的 接下来我将在容器化专栏中详细的为大家解释每一个指令的含义以及用法 专栏订阅传送门https blog csdn net qq
  • python中求输出1-3+5-7+9-......101的和

    第一种 i 0 sum 0 a 0 while i lt 102 if i gt 1 and i 4 1 sum i elif i 2 0 and i 1 a a i i 1 print sum a 第二种 a 1 b 3 sum1 0 s
  • 【Java】基于easy-poi实现Excel表导入与导出

    实现功能所需依赖如下
  • C++ 命名规范(Google)

    C 命名规范 Google 需要命名类型 命名规范 规范命名示例 命名形式反例 备注 通用命名规则 函数 变量 文件等命名应具有描述性 int num errors int nerr 除非缩写放到项目外也容易明确 否则尽量少使用缩写 文件命
  • 快手-开眼快创 Flutter 实践

    快手 开眼快创 Flutter 实践 本文主要介绍快手开眼快创 App 在 Flutter 上的一些实践 开眼快创 是围绕商业化广告创意构建的一款产品 目标人群涵盖供应商 代理商 广告主 商家号 视频行业从业者等 产品目标是提供智能化生产素
  • qnyutils工具库是基于纯JavaScript开发的,后续会扩展支持typescript。

    官网地址 qnyutils npm 介绍 前端项目开发常用js工具类 包括手机号码 身份证验证 中文校验 获取日期和根据日期格式获取日期或者转换日期格式 对象数组根据key分组 邮箱格式校验 获取历史时间 时间差 数组去重 多个对象数组去重
  • 【markdown 使用】

    这里写自定义目录标题 23232 欢迎使用Markdown编辑器 新的改变 功能快捷键 合理的创建标题 有助于目录的生成 如何改变文本的样式 插入链接与图片 如何插入一段漂亮的代码片 生成一个适合你的列表 创建一个表格 设定内容居中 居左
  • 2021年软件测试工具总结——测试管理工具

    每个软件研发团队都会搭建一套测试管理系统 由至少一个测试管理工具组成 用来管理各种测试活动 覆盖了整个测试过程 一个测试管理系统的构成如下所示 图片来源 全程软件测试 第14章 测试管理系统的核心是测试用例库和缺陷库 围绕测试用例的管理包括
  • MATLAB强化学习实战(十二) 创建自定义强化学习算法的智能体

    创建自定义强化学习算法的智能体 创建环境 定义策略 自定义智能体类 智能体属性 构造函数 相关函数 可选功能 创建自定义智能体 训练自定义智能体 自定义智能体仿真 本示例说明如何为您自己的自定义强化学习算法创建自定义智能体 这样做使您可以利
  • 服务器收不到客户端消息,java - 服务器没有收到来自客户端的消息(reader.readLine()== null?)...

    所以我一直在做一个简单的聊天 比有一台服务器和一群客户端连接到它们 在客户端 我有类ConnectionManager来管理创建套接字等 这是它的核心方法 java 服务器没有收到来自客户端的消息 reader readLine null
  • 目标检测新范式!港大同济伯克利提出Sparse R-CNN

    Sparse R CNN End to End Object Detection with Learnable Proposals 作者单位 港大 同济大学 字节AI Lab UC伯克利 沿着目标检测领域中Dense和Dense to Sp
  • java char与int互相转换

    1 int转char 将数字加一个 0 并强制类型转换为char 2 char转int 将字符减一个 0 即可 public class a public static void main String args System out pr
  • 【java】使pagehelper分页与mybatis-plus分页兼容存在

    问题 原先的功能接口都无法保存 出现如下错误 net sf jsqlparser statement select SetOperationList cannot be cast to net sf jsqlparser statement
  • 一张图告诉你,MES系统是什么

    MES系统 就要说到生产 涉及到人 钱 货 信息等资源 产 供 销 还有供应商 客户 合作伙伴 其中 产 就是生产 而生产管理就是通过对生产系统的战略规划 组织 指挥 实施 协调和控制 实现生产系统的物质转化 产品生产和价值提升的过程 擅长
  • 解决Python OpenCV 读取视频并抽帧出现error while decoding的问题

    解决Python OpenCV 读取视频抽帧出现error while decoding的问题 1 问题 2 解决 3 源代码 参考 1 问题 读取H264视频 抽帧视频并保存 报错如下 aac 00000220b9a07fc0 Input
  • 华为OD机试 - 火星文计算(Java)

    目录 题目描述 输入描述 输出描述 用例 题目解析 算法源码 题目描述 已知火星人使用的运算符为 其与地球人的等价公式如下 x y 2 x 3 y 4 x y 3 x y 2 其中x y是无符号整数 地球人公式按C语言规则计算 火星人公式中
  • Work with shaders and shader resources

    It s time to learn how to work with shaders and shader resources in developing your Microsoft DirectX game for Windows 8
  • 如何输出*.ply文件

    所谓ply文件格式 是由斯坦福大学开发的一套三维mesh模型数据格式 图形学领域内很多著名的模型数据 比如斯坦福的三维扫描数据库 其中包括很多文章中会见到的Happy Buddha Dragon Bunny兔子 最初的模型都是基于这个格式的
  • 夜莺(Nightingale)企业级监控平台

    元芳算法服务部署 监控篇 内部 简介 夜莺 Nightingale 是滴滴基础平台联合滴滴云研发和开源的企业级监控解决方案 旨在满足云原生时代企业级的监控需求 Nightingale在产品完成度 系统高可用 以及用户体验方面 达到了企业级的
  • java压缩文件工具类

    java压缩文件的各种方式及速度对比 1使用场景 2 maven依赖 3 压缩文件工具类 4 对比结果查看 1使用场景 开发过程中可能会用到压缩文件的需求 是用什么方式更快呢 本次就对几种常见的压缩方式做一个对比 2 maven依赖 引用c