首页 > 编程语言 >Java SpringBoot 7z 压缩、解压

Java SpringBoot 7z 压缩、解压

时间:2023-04-17 13:46:02浏览次数:45  
标签:Java SpringBoot String File input new 7z out

Java SpringBoot 7z 压缩、解压

cmd 7z 文件压缩

7z压缩测试
image

添加依赖

<dependency>
    <groupId>org.apache.commons</groupId>
    <artifactId>commons-compress</artifactId>
    <version>1.12</version>
</dependency>
<dependency>
    <groupId>org.tukaani</groupId>
    <artifactId>xz</artifactId>
    <version>1.5</version>
</dependency>

ZipFileUtil

package com.vipsoft.web.utils;

import org.apache.commons.compress.archivers.sevenz.SevenZArchiveEntry;
import org.apache.commons.compress.archivers.sevenz.SevenZFile;
import org.apache.commons.compress.archivers.sevenz.SevenZOutputFile;

import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class ZipFileUtil {
    /**
     * 7z文件压缩
     *
     * @param inputFile  待压缩文件夹/文件名
     * @param outputFile 生成的压缩包名字
     */

    public static void zip7z(String inputFile, String outputFile) throws Exception {
        File input = new File(inputFile);
        if (!input.exists()) {
            throw new Exception(input.getPath() + "待压缩文件不存在");
        }
        SevenZOutputFile out = new SevenZOutputFile(new File(outputFile));
        compress(out, input, null);
        out.close();
    }

    /**
     * @param name 压缩文件名,可以写为null保持默认
     */
    //递归压缩
    public static void compress(SevenZOutputFile out, File input, String name) throws IOException {
        if (name == null) {
            name = input.getName();
        }
        SevenZArchiveEntry entry = null;
        //如果路径为目录(文件夹)
        if (input.isDirectory()) {
            //取出文件夹中的文件(或子文件夹)
            File[] flist = input.listFiles();

            if (flist.length == 0)//如果文件夹为空,则只需在目的地.7z文件中写入一个目录进入
            {
                entry = out.createArchiveEntry(input,name + "/");
                out.putArchiveEntry(entry);
            } else//如果文件夹不为空,则递归调用compress,文件夹中的每一个文件(或文件夹)进行压缩
            {
                for (int i = 0; i < flist.length; i++) {
                    compress(out, flist[i], name + "/" + flist[i].getName());
                }
            }
        } else//如果不是目录(文件夹),即为文件,则先写入目录进入点,之后将文件写入7z文件中
        {
            FileInputStream fos = new FileInputStream(input);
            BufferedInputStream bis = new BufferedInputStream(fos);
            entry = out.createArchiveEntry(input, name);
            out.putArchiveEntry(entry);
            int len = -1;
            //将源文件写入到7z文件中
            byte[] buf = new byte[1024];
            while ((len = bis.read(buf)) != -1) {
                out.write(buf, 0, len);
            }
            bis.close();
            fos.close();
            out.closeArchiveEntry();
        }
    }

    /**
     * 7z解压缩
     * @param z7zFilePath	7z文件的全路径
     * @return  压缩包中所有的文件
     */
    public static Map<String, String> unZip7z(String z7zFilePath){

        String un7zFilePath = "";		//压缩之后的绝对路径

        SevenZFile zIn = null;
        try {
            File file = new File(z7zFilePath);
            un7zFilePath = file.getAbsolutePath().substring(0, file.getAbsolutePath().lastIndexOf(".7z"));
            zIn = new SevenZFile(file);
            SevenZArchiveEntry entry = null;
            File newFile = null;
            while ((entry = zIn.getNextEntry()) != null){
                //不是文件夹就进行解压
                if(!entry.isDirectory()){
                    newFile = new File(un7zFilePath, entry.getName());
                    if(!newFile.exists()){
                        new File(newFile.getParent()).mkdirs();   //创建此文件的上层目录
                    }
                    OutputStream out = new FileOutputStream(newFile);
                    BufferedOutputStream bos = new BufferedOutputStream(out);
                    int len = -1;
                    byte[] buf = new byte[(int)entry.getSize()];
                    while ((len = zIn.read(buf)) != -1){
                        bos.write(buf, 0, len);
                    }
                    bos.flush();
                    bos.close();
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            try {
                if (zIn != null)
                    zIn.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        Map<String, String> resultMap = getFileNameList(un7zFilePath, "");
        return resultMap;
    }

    /**
     * 获取压缩包中的全部文件
     * @param path	文件夹路径
     * @childName   每一个文件的每一层的路径==D==区分层数
     * @return  压缩包中所有的文件
     */
    private static Map<String, String> getFileNameList(String path, String childName) {
        System.out.println("path:" + path + "---childName:"+childName);
        Map<String, String> files = new HashMap<>();
        File file = new File(path); // 需要获取的文件的路径
        String[] fileNameLists = file.list(); // 存储文件名的String数组
        File[] filePathLists = file.listFiles(); // 存储文件路径的String数组
        for (int i = 0; i < filePathLists.length; i++) {
            if (filePathLists[i].isFile()) {
                files.put(fileNameLists[i] + "==D==" + childName, path + File.separator + filePathLists[i].getName());
            } else {
                files.putAll(getFileNameList(path + File.separator + filePathLists[i].getName(), childName + "&" + filePathLists[i].getName()));
            }
        }
        return files;
    }
}

Test

package com.vipsoft.web;

import com.vipsoft.web.utils.ZipFileUtil;
import org.junit.jupiter.api.Test; 

public class ZipTest {

    @Test
    void zip7zTest() throws Exception {
        String inputPath = "D:\\temp\\logs\\logs";
        String outputPath = "D:\\temp\\logs\\1.7z";
        ZipFileUtil.zip7z(inputPath, outputPath); 
    }

    @Test
    void unZip7zTest() throws Exception {
        String outputPath = "D:\\temp\\logs\\1.7z";
        ZipFileUtil.unZip7z(outputPath);
    }
}

标签:Java,SpringBoot,String,File,input,new,7z,out
From: https://www.cnblogs.com/vipsoft/p/17325574.html

相关文章

  • Java开发笔记13(树的结构修改记录)
    1.Controller:/***区域树生成*/@GetMapping("/list")privateResultregionTree(){Stationstation=getStation(getUser());StringstationCode=station.getStationTelecode();List<NewTreeVo>tree=stationInfRelaService.regionTree(stat......
  • Java中线程的常用操作-后台线程、自定义线程工厂ThreadFactpry、join加入一个线程、线
    场景Java中Thread类的常用API以及使用示例:https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/details/126596884上面讲了Thread的常用API,下面记录下线程的一些常用操作。注:博客:https://blog.csdn.net/badao_liumang_qizhi实现后台线程后台线程,是指运行时在后台提供的一......
  • Springboot使用RestTemplate发送Post请求postForEntity (application/json)的坑
    当使用RestTemplate进行http请求时,的确很方便,但是当需要进行post请求时遇到了坑1POST传递参数:采用LinkedMultiValueMap,不能使用HashMapStringurl='http://posturl';MultiValueMap<String,String>map=newLinkedMultiValueMap<String,String>();map.add(......
  • 【迭代器设计模式详解】C/Java/JS/Go/Python/TS不同语言实现
    简介迭代器模式(IteratorPattern),是一种结构型设计模式。给数据对象构建一套按顺序访问集合对象元素的方式,而不需要知道数据对象的底层表示。迭代器模式是与集合共存的,我们只要实现一个集合,就需要同时提供这个集合的迭代器,就像Java中的Collection,List、Set、Map等,这些集合都有自......
  • springboot整合swagger2
     1.正文1.1什么是swagger2Swagger是一个规范和完整的框架,用于生成、描述、调用和可视化RESTful风格的Web服务的接口文档 .接口:controller相应的路径方法Swagger2是一款前后端分离开发中非常实用的API管理工具,它可以帮助开发者根据约定规范自动生成API文档,并支持......
  • java json 四个格式
    java官方<dependency><groupId>org.json</groupId><artifactId>json</artifactId><version>20220320</version></dependency>codeJSONObjectjsonObject=newJSONObject();jsonObject.put("secretKey......
  • 笔记springboot0410
    1.课程大纲-springboot框架1.什么是Springboot以及Springboot的特点。2.快速搭建springboot项目3.springboot常用的配置文件类型.4.读取springboot配置文件的内容5.多环境配置6.springboot整合数据源。7.springboot整合mybatis.8.springboot整合定时器。2.什么......
  • idea Java json 复制字符串会出现空格的问题
    普通JSON{"secretKey":"2513e9c533c14271a1bc8a52eacecebe","appKey":"19b9257a1f464e93b087af9d12572ce1"}复制idea{\"secretKey\":\"2513e9c533c14271a1bc8a52eacecebe\",\"appKey\":\&......
  • java环境变量
    jdk安装路径C:\ProgramFiles\Java\jdk1.6.0_21java_homeC:\ProgramFiles\Java\jdk1.6.0_21classpath.;%JAVA_HOME%lib;%JAVA_HOME%lib\tools.jarPath%JAVA_HOME%\bin;%JAVA_HOME%\jre\bin检查是否安装成功java-version  ant环境的配置配置ant 和 java的环境  ......
  • Java位运算符
    前置知识原码、反码、补码-原码:第一位表示符号,其余位表示值。如2原码:00000010;-2原码:10000010-反码:正数的反码是原码本身,负数的反码在原码基础上,符号位不变,其他位取反。如:2反码:00000010;-2反码:11111101-补码:正数的反码是原码本身,负数的补码在原码基础上,符号位不变,其他......