Administrator
发布于 2020-12-31 / 2518 阅读 / 0 评论 / 0 点赞

java中将多文件字节流压缩成zip

java中将多文件字节流压缩成zip

  • 核心就是使用java.util.zip包中的ZipOutputStream

  • 直接上核心代码

/**
     *
     * @param zipFilePath zip保存路径
     * @param zipFileName zip文件名
     * @param byteList 文件字节码Map,k:fileName,v:byte[]
     */
public static void zipFile(String zipFilePath, String zipFileName, Map<String, byte[]> byteList) {
	//如果文件夹不存在就创建文件夹,防止报错
        File file = new File(zipFilePath);
        if (!file.exists() && !file.isDirectory()) {
            LOGGER.warn("文件夹不存在,创建新文件夹!");
            file.mkdirs();
        }

        try {
            FileOutputStream fileOutputStream = new FileOutputStream(String.format("%s%s%s", zipFilePath, zipFileName, ".zip"));
            ZipOutputStream zipOutputStream = new ZipOutputStream(fileOutputStream);
            byteList.forEach((k, v) -> {
                //写入一个条目,我们需要给这个条目起个名字,相当于起一个文件名称
                try {
                    zipOutputStream.putNextEntry(new ZipEntry(k));
                    zipOutputStream.write(v);
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.print("写入文件失败");
                }
            });
            //关闭条目
            zipOutputStream.closeEntry();
            zipOutputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
            System.out.print("压缩文件失败");
        }
    }
  • 调用方法
Map<String, byte[]> byteFileMap = new HashMap<>();
byteFileMap.put(“testfile.txt”, "我是文件内容".getBytes());
String zipFileName = LocalDateTime.now();
String zipFilePath = "/opt/user/"
ZipUtils.zipFile(zipFilePath, zipFileName, byteFileMap);

评论