java (7z,zip)压缩和解压

1.引入jar包

<dependencies>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-compress</artifactId>
            <version>1.20</version>
        </dependency>
        <dependency>
            <groupId>org.apache.commons</groupId>
            <artifactId>commons-lang3</artifactId>
            <version>3.11</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.18</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.slf4j</groupId>
            <artifactId>slf4j-api</artifactId>
            <version>2.0.0-alpha1</version>
        </dependency>
        <dependency>
            <groupId>org.tukaani</groupId>
            <artifactId>xz</artifactId>
            <version>1.8</version>
        </dependency>
    </dependencies>

2.创建压缩工具类CompressUtils

/**
 * 压缩文件
 */
@Slf4j
public class CompressUtils {

    /**
     * 7z压缩
     * @param inputFile 要压缩的目录
     * @param outputFile 压缩文件存放目录
     * @throws IOException
     */
    public static void compress7z(String inputFile,String outputFile) {
        File input = new File(inputFile);
        try (SevenZOutputFile out = new SevenZOutputFile(new File(outputFile))) {
            compression7z(out,input,null);
        }catch (Exception ex){
            log.error("compress7z error:",ex);
        }
    }

    /**
     * 7z压缩  递归压缩方法
     * @param out  输出流
     * @param input 输出流
     * @param name 带要压缩的目录的文件
     * @throws IOException
     */
    public static void compression7z(SevenZOutputFile out , File input, String name) throws IOException {
        //7z实体
        SevenZArchiveEntry entry ;
        String fileName = StringUtils.isNotBlank(name)?(name+ File.separator):"";
        //判断是否是目录
        if(input.isDirectory()){
            File[] flist = input.listFiles();
            if(flist.length == 0){
                entry = out.createArchiveEntry(input,fileName);
                out.putArchiveEntry(entry);
            }else{
                for(int i = 0; i < flist.length ;i++){
                    compression7z(out,flist[i],fileName+ flist[i].getName());
                }
            }
        //如果是文件写入
        }else{
            try (FileInputStream fos = new FileInputStream(input); BufferedInputStream bufferedInputStream = new BufferedInputStream(fos)) {
                entry = out.createArchiveEntry(input,name);
                out.putArchiveEntry(entry);
                int len = -1;
                byte[] buf = new byte[4096];
                while((len = bufferedInputStream.read(buf)) != -1){
                    out.write(buf,0,len);
                }
                out.closeArchiveEntry();
            }catch (Exception ex){
                log.error("compress7z error:",ex);
            }
        }
    }

    /**
     * zip压缩
     * @param inputFile 要压缩的文件或目录
     * @param outputFile 压缩后的文件存放目录
     */
    public static void compressZip(String inputFile,String outputFile) {
        try(ZipOutputStream out = new ZipOutputStream(new FileOutputStream(new File(outputFile)));) {
            compressZip(out, new File(inputFile), null);
        }catch (Exception ex){
            log.error("compressZip error:" , ex);
        }
    }

    /**
     * zip压缩   递归压缩方法
     * @param out
     * @param in
     * @param name
     * @throws IOException
     */
    public static void compressZip(ZipOutputStream out,File in,String name) {
        try {
            if (in.isDirectory()) {
                File[] flist = in.listFiles();
                name = StringUtils.isBlank(name) ? "" : (name + File.separator);
                //空目录
                if (null == flist || flist.length == 0) {
                    out.putNextEntry(new ZipEntry(name));
                } else {
                    for (File file : flist) {
                        compressZip(out, file, name + file.getName());
                    }
                }
            } else {
                try(FileInputStream fileInputStream = new FileInputStream(in)) {
                    out.putNextEntry(new ZipEntry(name));
                    int size;
                    byte[] bytes = new byte[4096];
                    while ((size = fileInputStream.read(bytes)) != -1) {
                        out.write(bytes, 0, size);
                    }
                }
            }
        }catch (Exception ex){
            log.error("compressZip error:",ex);
        }
    }

}

4.创建解压工具类DecompressUtils

/**
 * 解压缩
 */
@Slf4j
public class DecompressUtils {
    /**
     * 解压7z
     * @param inputFile  压缩文件
     * @param outputFile  解压的目录
     */
    public static void decompress7z(String inputFile,String outputFile){

        try(SevenZFile sevenZFile = new SevenZFile(new File(inputFile))) {
            Iterator<SevenZArchiveEntry> iterator = sevenZFile.getEntries().iterator();
            while (iterator.hasNext()){
                SevenZArchiveEntry nextEntry = iterator.next();
                String name = nextEntry.getName();
                String outPath = outputFile + File.separator + name;
                if(outPath.lastIndexOf("\\") != -1){
                    File outPathFile = new File(outPath);
                    if(!outPathFile.getParentFile().exists()){
                        outPathFile.getParentFile().mkdirs();
                    }
                    if(!outPathFile.exists()){
                        outPathFile.createNewFile();
                    }
                }
                try(FileOutputStream outputStream = new FileOutputStream(outPath);
                InputStream inputStream = sevenZFile.getInputStream(nextEntry)) {
                    byte[] bytes = new byte[1024];
                    int size;
                    while ((size = inputStream.read(bytes)) != -1) {
                        outputStream.write(bytes, 0, size);
                    }
                }
            }
        } catch (IOException e) {
            log.error("decompress7z error:",e);
        }
    }

    /**
     * 解压zip文件
     * @param inpath
     * @param outpath
     */
    public static void decompressZip(String inpath ,String outpath){
        try {
            ZipFile zipFile = new ZipFile(inpath);
            Enumeration<? extends ZipEntry> entries = zipFile.entries();
            while(entries.hasMoreElements()){
                ZipEntry zipEntry = entries.nextElement();
                String name = zipEntry.getName();
                String outputPath = outpath + File.separator + name;
                if(outputPath.lastIndexOf("\\") != -1){
                    File file = new File(outputPath);
                    if(!file.getParentFile().exists()){
                        file.getParentFile().mkdirs();
                    }
                    if(!file.exists()){
                        file.createNewFile();
                    }
                }
                try(InputStream inputStream = zipFile.getInputStream(zipEntry);FileOutputStream fileOutputStream = new FileOutputStream(outputPath)) {
                    int size;
                    byte[] bytes = new byte[1024];
                    while ((size = inputStream.read(bytes)) != -1) {
                        fileOutputStream.write(bytes, 0, size);
                    }
                }
            }
        }catch (Exception ex){
            log.error("decompresszip error" ,ex);
        }
    }
}

4.测试程序

public static void main(String[] args) {
        CompressUtils.compress7z("F:\\download\\chrome","E:\\test\\download.7z");
        System.out.println("compress7z end");
        DecompressUtils.decompress7z("E:\\test\\download.7z","E:\\test\\7z");
        System.out.println("decompress7z end");
        CompressUtils.compressZip("F:\\download\\chrome","E:\\test\\download.zip");
        System.out.println("compresszip end");
        DecompressUtils.decompressZip("E:\\test\\download.zip","E:\\test\\zip");
        System.out.println("decompresszip end");
    }

5.还可使用hutool  jar包中的ZipUtils

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值