使用apache的commons-compress可以实现文件的7z解压缩功能

java使用7z对文件压缩可以使文件大小被压缩的很小,便于对文件的归档处理,使用apache的commons-compress可以实现文件的7z解压缩功能

1.压缩

/**
 * 7z文件压缩
 *
 * @param inputFile  待压缩文件夹/文件名
 * @param outputFile 生成的压缩包名字
 */
public static void compress7z(String inputFile, String outputFile) {
    log.info("开始7z压缩本地路径{}的相关日志到{}压缩文件中", inputFile, outputFile);
    StopWatch watch = new StopWatch();
    watch.start("7z压缩");
    SevenZOutputFile outArchive = null;
    try {
        File input = new File(inputFile);
        if (!input.exists()) {
            throw new RuntimeException(input.getPath() + "待压缩文件不存在");
        }
        File output = new File(outputFile);
        outArchive = new SevenZOutputFile(output);
        // 递归压缩
        compress(outArchive, input, null);
    } catch (Exception e) {
        log.error("7z文件压缩出现异常源路径{},目标路径{}", inputFile, outputFile, e);
        throw new RuntimeException("7z文件压缩出现异常");
    } finally {
        // 关闭
        closeSevenZOutputFile(outArchive);
    }

    watch.stop();
    log.info("结束7z压缩本地路径{}的相关日志到{}压缩文件中,耗时{}ms", inputFile, outputFile, watch.getTotalTimeMillis());
}

2.解压

/**
 * 7z文件解压
 *
 * @param inputFile   待解压文件名
 * @param destDirPath 解压路径
 */
public static void unCompress7z(String inputFile, String destDirPath) throws Exception {
    StopWatch watch = new StopWatch();
    watch.start("7z解缩");
    // 获取当前压缩文件
    File srcFile = new File(inputFile);
    // 判断源文件是否存在
    if (!srcFile.exists()) {
        throw new Exception(srcFile.getPath() + "所指文件不存在");
    }
    // 开始解压
    SevenZFile zIn = new SevenZFile(srcFile);
    SevenZArchiveEntry entry = null;
    File file = null;
    while ((entry = zIn.getNextEntry()) != null) {
        if (!entry.isDirectory()) {
            file = new File(destDirPath, entry.getName());
            if (!file.exists()) {
                // 创建此文件的上级目录
                new File(file.getParent()).mkdirs();
            }
            OutputStream out = new FileOutputStream(file);
            BufferedOutputStream bos = new BufferedOutputStream(out);
            int len = -1;
            byte[] buf = new byte[1024];
            while ((len = zIn.read(buf)) != -1) {
                bos.write(buf, 0, len);
            }
            // 关流顺序,先打开的后关闭
            bos.close();
            out.close();
        }
    }

    watch.stop();
    log.info("结束7z解压,耗时{}ms", watch.getTotalTimeMillis());

}

3.测试

package com.common.util.sevenz.controller;

import com.common.util.sevenz.SevenZipUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * @author
 * @Describe 功能描述
 * @date
 */
@RestController
public class SevenzTestController {

    String srcPath = "C:\\Users\\kinson\\Desktop\\7zTest";
    String dest7zFilePath = "C:\\Users\\kinson\\Desktop\\7zTest.7z";

    String destPath = "C:\\Users\\kinson\\Desktop\\un7z";

    @RequestMapping(value = "compress7z")
    public void compress7z(HttpServletResponse response, String type) throws IOException {
        if (StringUtils.isEmpty(type)) {
            // 浏览器响应
            // 浏览器响应返回
            response.reset();
            // 设置response的header,response为HttpServletResponse接收输出流
            response.setContentType("application/octet-stream");
            String sevenzFileName = "7zFile-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern(
                    "yyyyMMddHHmmss")) + ".7z";
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(sevenzFileName, "UTF-8"));

            // 压缩为7z
            SevenZipUtil.compress7z(srcPath, dest7zFilePath);
            // 将压缩好的7z响应给浏览器
            File file = new File(dest7zFilePath);
            if (null != file && file.isFile()) {
                ServletOutputStream os = response.getOutputStream();
                FileInputStream fis = new FileInputStream(file);
                BufferedInputStream bis = new BufferedInputStream(fis);
                int len = -1;
                // 将源文件写入到输出流
                byte[] buf = new byte[1024];
                while ((len = bis.read(buf)) != -1) {
                    os.write(buf, 0, len);
                }

                bis.close();
                fis.close();
                os.close();
            }
        } else {
            // 写到目标文件
            SevenZipUtil.compress7z(srcPath, dest7zFilePath);
        }
    }

    @RequestMapping(value = "unCompress7z")
    public void unCompress7z() throws Exception {
        // 解压
        SevenZipUtil.unCompress7z(dest7zFilePath, destPath);
    }
}

完整代码见 SevenZipUtil

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
commons-compress是一个用Java编写的开源压缩库,支持多种压缩格式,包括zip、gzip、tar等。其中,zip是一种常见的分卷压缩格式,可以将大文件分割成多个小文件进行压缩。 要使用commons-compress实现zip文件分卷压缩,可以按照以下步骤进行: 1. 导入commons-compress库 在Java项目中使用commons-compress库,需要先将其导入到项目中。可以通过Maven或手动下载jar包的方式导入。 2. 创建ZipArchiveOutputStream对象 使用ZipArchiveOutputStream类可以将文件压缩成zip格式。在创建ZipArchiveOutputStream对象时,需要指定输出流和zip文件的编码方式。 ```java OutputStream outputStream = new FileOutputStream("output.zip"); ZipArchiveOutputStream zipOutputStream = new ZipArchiveOutputStream(outputStream); zipOutputStream.setEncoding("UTF-8"); ``` 3. 添加文件到zip文件中 可以通过ZipArchiveEntry类创建需要添加到zip文件中的文件对象。对于需要分卷压缩文件,可以使用ZipSplitOutputStream类将其分割成多个小文件。 ```java File file = new File("largefile.txt"); ZipArchiveEntry entry = new ZipArchiveEntry(file, file.getName()); ZipSplitOutputStream splitOutputStream = new ZipSplitOutputStream(zipOutputStream, 1024 * 1024); splitOutputStream.putNextEntry(entry); FileInputStream inputStream = new FileInputStream(file); byte[] buffer = new byte[1024]; int len; while ((len = inputStream.read(buffer)) > 0) { splitOutputStream.write(buffer, 0, len); } inputStream.close(); splitOutputStream.closeArchiveEntry(); ``` 这里将largefile.txt文件分割成大小为1MB的小文件,每个小文件都是一个ZipArchiveEntry对象。使用ZipSplitOutputStream的putNextEntry方法可以将小文件添加到zip文件中。 4. 关闭ZipArchiveOutputStream对象 完成文件添加后,需要关闭ZipArchiveOutputStream对象,以便将所有缓存的数据写入到zip文件中。 ```java zipOutputStream.finish(); zipOutputStream.close(); ``` 通过以上步骤,就可以使用commons-compress实现zip文件分卷压缩了。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值