【导出】多文件导出生成zip压缩包

/**
     * 生成zip压缩包
     * @param filePathList  文件路径列表
     * @param zipFileName   zip文件路径名称
     */
    public void createZipFiles(List filePathList, String zipFileName) {
        FileOutputStream fos = null;
        ZipOutputStream zos = null;
        try {
            fos = new FileOutputStream(zipFileName);
            zos = new ZipOutputStream(fos);
            for (String filePath : filePathList) {
                File file = new File(filePath);
                if (!file.exists()) {
                    System.err.println("文件不存在: " + filePath);
                    continue;
                }

                // 使用文件名作为ZIP条目名
                ZipEntry zipEntry = new ZipEntry(file.getName());
                zos.putNextEntry(zipEntry);

                // 读取文件内容并写入ZIP
                try (FileInputStream fis = new FileInputStream(file)) {
                    byte[] buffer = new byte[1024];
                    int length;
                    while ((length = fis.read(buffer)) > 0) {
                        zos.write(buffer, 0, length);
                    }
                }
                zos.flush();
                zos.closeEntry();
                zos.close();
            }
            fos.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != fos) {
                    fos.close();
                }
                if (null != zos) {
                    zos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

你可能感兴趣的:(【导出】多文件导出生成zip压缩包)