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

Java SpringBoot 7z 压缩、解压

时间:2023-04-23 12:33:31浏览次数:47  
标签:Java SpringBoot String File input new 7z out

Java SpringBoot 7z 压缩、解压

Java SpringBoot 7z 压缩、解压

cmd 7z 文件压缩

7z压缩测试

Java SpringBoot 7z 压缩、解压_Test

添加依赖

<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://blog.51cto.com/u_15116285/6217056

相关文章

  • jackson将java对象转换为json字符串
    1.1. 下载jacksonJackson可以轻松的将Java对象转换成json对象和xml文档,同样也可以将json、xml转换成Java对象。相比json-lib框架,Jackson所依赖的jar包较少,简单易用并且性能也要相对高些。而且Jackson社区相对比较活跃,更新速度也比较快。下载地址:http://jackson.codehaus.org/1......
  • 力扣844(Java)-比较含退格的字符串(简单)
    题目:给定s和t两个字符串,当它们分别被输入到空白的文本编辑器后,如果两者相等,返回true。#代表退格字符。注意:如果对空文本输入退格字符,文本继续为空。 示例1:输入:s="ab#c",t="ad#c"输出:true解释:s和t都会变成"ac"。示例2:输入:s="ab##",t="c#d#"输出:true......
  • java:文件写入BufferedOutputStream写入字节和PrintWriter写入字符
    BufferedOutputStream和FileOutputStream写入二进制字节方法定义publicBufferedOutputStream(OutputStreamout){示例BufferedOutputStreamwriter=newBufferedOutputStream(newFileOutputStream("demo.txt"));writer.write("helloworld".getBytes());w......
  • SpringBoot中底层对 /health 的请求是怎么处理的?
     在SpringBoot应用程序中,/health端点是通过HealthEndpointbean来处理的。当您访问/health端点时,SpringBoot会调用HealthEndpointbean的health()方法来检查应用程序的健康状态,并返回相应的响应。HealthEndpointbean是通过HealthEndpointAutoConfiguration自......
  • java使用数组实现队列
    1.1. 队列的数据结构队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头。1.2. Java实现QueueTestpackagech04;publicclassQ......
  • java用数组实现栈
    1.1. 栈的数据结构栈是一种先进后出的数据结果,只能在一端(称为栈顶(top))对数据项进行插入和删除。1.2. Java实现StackTestpackagech04;publicclassStackTest{publicstaticvoidmain(String[]args){ArrayStackstack=newArrayStack(10);......
  • Json字符串转换为java对象
    1.  Json字符串转换为java对象1.1. Json字符串转换为javabeanJson2Bean.javapackagejackson;importjava.io.IOException;importorg.codehaus.jackson.map.ObjectMapper;publicclassJson2Bean{publicstaticvoidmain(String[]args)throwsIOExcepti......
  • java利用json-lib操作json
    1.1. 下载json-lib.jarhttp://sourceforge.net/projects/json-lib/files/json-lib/1.2. Java对象转换为json1.2.1.  Map对象转换为jsonMap2Json.javapackagejson;importjava.util.HashMap;importjava.util.Map;importnet.sf.json.JSONArray;publicclassMap2......
  • Java使用maven-invoker插件进行maven相关操作
    官方文档地址:https://maven.apache.org/shared/maven-invoker/index.htmlApacheMavenInvoker在许多情况下,工具(包括Maven本身)可能希望在干净的环境中启动Maven构建。为什么呢?也许您希望避免Maven插件产生的副作用污染当前系统环境。也许您想从与当前${user.dir}不同的工作目......
  • 数据结构与算法跳表之java实现
    跳表一个有序链表的搜索、添加、删除的平均时间复杂度都为O(n),那么能否利用二分搜索优化有序链表,将搜索、添加、删除的平均时间复杂度降低至O(logn)呢?链表没有像数组那样的高效随机访问(O(1)时间复杂度),所以不能像有序数组那样直接进行二分搜索优化。那有没有其他办法让有序链表的搜......