使用java自带的API实现zip解压缩

java处理文件时,有时候需要对文件进行zip压缩操作,可以使用java自带的api实现解压缩功能。

1.压缩

1.1 将文件压缩到指定的zip文件

/**
 * 压缩多个文件成一个zip文件
 *
 * @param srcFiles:源文件列表
 * @param destZipFile:压缩后的文件
 */
public static void toZip(File[] srcFiles, File destZipFile) {
    byte[] buf = new byte[1024];
    try {
        // ZipOutputStream类:完成文件或文件夹的压缩
        ZipOutputStream out = new ZipOutputStream(new FileOutputStream(destZipFile));
        for (int i = 0; i < srcFiles.length; i++) {
            FileInputStream in = new FileInputStream(srcFiles[i]);
            // 给列表中的文件单独命名
            out.putNextEntry(new ZipEntry(srcFiles[i].getName()));
            int len;
            while ((len = in.read(buf)) > 0) {
                out.write(buf, 0, len);
            }
            out.closeEntry();
            in.close();
        }
        out.close();
        log.info("压缩完成.");
    } catch (Exception e) {
        log.error("压缩出错,", e);
    }
}

1.2 通过浏览器响应下载文件

  • 方式一
/**
 * 压缩成ZIP 方法1
 *
 * @param srcDir           压缩文件夹路径
 * @param out              压缩文件输出流
 * @param keepDirStructure 是否保留原来的目录结构,true:保留目录结构;
 *                         false:所有文件跑到压缩包根目录下
 *                         (注意:不保留目录结构可能会出现同名文件,会压缩失败)
 * @throws RuntimeException 压缩失败会抛出运行时异常
 */
public static void toZip(String srcDir, OutputStream out, boolean keepDirStructure) {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start("toZip-1");
    ZipOutputStream zos = null;
    try {
        zos = new ZipOutputStream(out);
        File sourceFile = new File(srcDir);
        compress(sourceFile, zos, sourceFile.getName(), keepDirStructure);
    } catch (Exception e) {
        log.error("压缩zip出错,", e);
        throw new RuntimeException("压缩zip出错");
    } finally {
        close(zos);
    }
    stopWatch.stop();
    log.info("toZip-1 共耗时:{}", stopWatch.getTotalTimeMillis());
}
  • 方式二
/**
 * 压缩成ZIP 方法2
 *
 * @param srcFiles 需要压缩的文件列表
 * @param out      压缩文件输出流
 * @throws RuntimeException 压缩失败会抛出运行时异常
 */
public static void toZip(List<File> srcFiles, OutputStream out) throws RuntimeException {
    StopWatch stopWatch = new StopWatch();
    stopWatch.start("toZip-2");
    ZipOutputStream zos = null;
    try {
        zos = new ZipOutputStream(out);
        for (File sourceFile : srcFiles) {
            byte[] buf = new byte[BUFFER_SIZE];
            zos.putNextEntry(new ZipEntry(sourceFile.getName()));
            int len;
            FileInputStream in = new FileInputStream(sourceFile);
            while ((len = in.read(buf)) != -1) {
                zos.write(buf, 0, len);
            }
            zos.closeEntry();
            in.close();
        }
    } catch (Exception e) {
        log.error("压缩zip出错,", e);
        throw new RuntimeException("压缩zip出错");
    } finally {
        close(zos);
    }
    stopWatch.stop();
    log.info("toZip-2 共耗时:{}", stopWatch.getTotalTimeMillis());
}

2.解压

/**
 * 解压文件
 *
 * @param zipFile:需要解压缩的文件
 * @param descDir:解压后的目标目录
 */
public static void unZipFiles(File zipFile, String descDir) throws IOException {
    File destFile = new File(descDir);
    if (!destFile.exists()) {
        destFile.mkdirs();
    }
    // 解决zip文件中有中文目录或者中文文件
    ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));
    for (Enumeration entries = zip.entries(); entries.hasMoreElements(); ) {
        ZipEntry entry = (ZipEntry) entries.nextElement();
        InputStream in = zip.getInputStream(entry);
        String curEntryName = entry.getName();
        // 判断文件名路径是否存在文件夹
        int endIndex = curEntryName.lastIndexOf('/');
        // 替换
        String outPath = (descDir + curEntryName).replaceAll("\\*", "/");
        if (endIndex != -1) {
            File file = new File(outPath.substring(0, outPath.lastIndexOf("/")));
            if (!file.exists()) {
                file.mkdirs();
            }
        }

        // 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
        File outFile = new File(outPath);
        if (outFile.isDirectory()) {
            continue;
        }
        OutputStream out = new FileOutputStream(outPath);
        byte[] buf1 = new byte[1024];
        int len;
        while ((len = in.read(buf1)) > 0) {
            out.write(buf1, 0, len);
        }
        in.close();
        out.close();
    }
    log.info("解压{}成功", zipFile.getName());
}

3. 测试

package com.common.util.zip.controller;

import com.common.util.zip.ZipUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

/**
 * @author
 * @Describe 功能描述
 * @date
 */
@RestController
@Slf4j(topic = "ZipController")
public class ZipController {

    String srcDir = "C:\\Users\\kinson\\Desktop\\zipTest";
    String desDir = "C:\\Users\\kinson\\Desktop\\unzip\\";

    String desZipFilename = "C:\\Users\\kinson\\Desktop\\zipTest\\dest.zip";

    String desZipFilePath = "C:\\Users\\kinson\\Desktop\\";

    @RequestMapping(value = "toZip")
    public void toZip(HttpServletRequest request, HttpServletResponse response, String type) throws IOException {
        if (StringUtils.isEmpty(type)) {
            // 浏览器响应返回
            response.reset();
            // 设置response的header,response为HttpServletResponse接收输出流
            response.setContentType("application/zip");
            String zipFileName = "zipFile-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern(
                    "yyyyMMddHHmmss")) + ".zip";
            response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(zipFileName, "UTF-8"
            ));
            ZipUtils.toZip(srcDir, response.getOutputStream(), true);
        } else if (StringUtils.equals(type, "2")) {
            // 浏览器响应返回2
            File file = new File(srcDir);
            if (file.isDirectory() && file.listFiles().length > 0) {
                File[] files = file.listFiles();
                List<File> fileList = Arrays.asList(files);
                response.reset();
                // 设置response的header,response为HttpServletResponse接收输出流
                response.setContentType("application/zip");
                String zipFileName = "zipFile2-" + LocalDateTime.now().format(DateTimeFormatter.ofPattern(
                        "yyyyMMddHHmmss")) + ".zip";
                response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(zipFileName, "UTF-8"
                ));
                ZipUtils.toZip(fileList, response.getOutputStream());
            }
        } else if (StringUtils.equals(type, "3")) {
            // 指定目录
            File file = new File(srcDir);
            File desZipFile = new File(desZipFilename);
            if (file.isDirectory() && file.listFiles().length > 0) {
                File[] files = file.listFiles();
                ZipUtils.toZip(files, desZipFile);
            }
        } else {
            log.info("type is {}", type);
        }

    }

    @RequestMapping(value = "unZip")
    public void unZip(String zipFilename) throws IOException {
        Assert.isTrue(StringUtils.isNotEmpty(StringUtils.trim(zipFilename)));
        File file = new File(desZipFilePath + zipFilename + ".zip");
        ZipUtils.unZipFiles(file, desDir);
    }
}

完整代码见 ZipUtils

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值