跳至主要內容

Zip压缩

程序员李某某大约 2 分钟

Zip压缩

@Slf4j
public class ZipUtils {
    /**
     * 根据url集合打包,返回字节数组
     */
    public static byte[] getZipAsByteArray(List<String> urlList) {
        try {
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            // 创建 ZipOutputStream 对象
            try (ZipOutputStream out = new ZipOutputStream(outputStream)) {
                onZip(urlList, out);
            }
            log.info("压缩包转换为字节数组成功!");
            return outputStream.toByteArray();
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 根据url集合打包,返回输入流
     *
     * @param urlList
     * @return
     */
    public static InputStream getZipAsInputStream(List<String> urlList,String zipFileName) {
        try {
            // 创建 ZipOutputStream 对象
            try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName))) {
                onZip(urlList, out);
            } catch (IOException e) {
                e.printStackTrace();
                log.error("#### 压缩时出现错误,e = ", e);
            }

            // 将压缩包转化为输入流
            try (FileInputStream fis = new FileInputStream(zipFileName)) {
                byte[] data = new byte[fis.available()];
                fis.read(data);
                InputStream bais = new ByteArrayInputStream(data);
                log.info("压缩包转换为输入流成功!");
                return bais;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 根据url集合打包,返回前端字节流
     * @param response
     * @param urlList
     * @param zipFileName
     */
    public static void responseZip(HttpServletResponse response, List<String> urlList, String zipFileName) {
        try (FileOutputStream fos = new FileOutputStream(zipFileName);
             ZipOutputStream zos = new ZipOutputStream(fos)) {
            onZip(urlList, zos);

            File zipFile = new File(zipFileName);
            byte[] zipData = Files.readAllBytes(zipFile.toPath());

            // 设置响应头部信息
            response.setHeader("Content-Type", "application/octet-stream");
            response.setHeader("Content-Disposition", "attachment;filename=" + zipFileName);

            ServletOutputStream out = response.getOutputStream();
            out.write(zipData); // 将压缩包数据响应给前端
            out.flush();
        } catch (IOException e) {
            e.printStackTrace();
            log.error("#### 压缩时出现错误,e = ", e);
        }
    }


    /**
     * 根据url集合打包,下载到本地
     *
     * @param urlList
     * @param savePath
     */
    public static void DownloadZipToLocal(List<String> urlList, String savePath,String zipFileName) {
        try {
            try (ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFileName))) {
                // 遍历 URL 列表,将每个 URL 的资源添加到压缩包中
                onZip(urlList, out);
            }
            log.info("正在下载压缩包...");
            File zipFile = new File(zipFileName);
            byte[] zipData = new byte[(int) zipFile.length()];
            try (FileInputStream in = new FileInputStream(zipFile)) {
                in.read(zipData);
            }

            File saveDir = new File(savePath);
            if (!saveDir.exists()) {
                saveDir.mkdir();
            }

            File saveFile = new File(saveDir.getAbsolutePath() + File.separator + zipFileName);
            try (OutputStream out = new FileOutputStream(saveFile)) {
                out.write(zipData); // 将压缩包数据写入本地文件中
                out.flush();
                log.info("压缩包下载成功:" + saveFile.getAbsolutePath());
            }
            // 删除临时文件
            zipFile.delete();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /**
     * 压缩
     *
     * @param urlList
     * @param out
     * @throws IOException
     */
    private static void onZip(List<String> urlList, ZipOutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        for (String urlString : urlList) {
            URL url = new URL(urlString);

            // 从 URL 打开输入流
            try (InputStream in = url.openStream(); BufferedInputStream bis = new BufferedInputStream(in)) {
                // 获取 URL 的文件名
                String fileName = getFileNameFromUrl(urlString);

                // 创建压缩包条目
                ZipEntry entry = new ZipEntry(fileName);
                out.putNextEntry(entry);

                // 读取输入流中的数据并写入压缩包中
                int len;
                while ((len = bis.read(buffer)) > 0) {
                    out.write(buffer, 0, len);
                }
                // 关闭当前条目
                out.closeEntry();
            }
        }
        // 关闭 ZipOutputStream
        out.close();
        log.info("压缩包创建成功!");
    }


    /**
     * 获取文件名
     *
     * @param urlString
     * @return
     */
    private static String getFileNameFromUrl(String urlString) {
        urlString = urlString.split("\\?")[0];
        int lastSlashIndex = urlString.lastIndexOf("/");
        if (lastSlashIndex >= 0 && lastSlashIndex < urlString.length() - 1) {
            return urlString.substring(lastSlashIndex + 1);
        } else {
            log.error("####### 文件名称获取失败,urlString = {}", urlString);
            return "unknown";
        }
    }
}


上次编辑于:
贡献者: ext.liyuanhao3