简单的ZIP解压缩文件工具

简单的ZIP解压缩文件工具

import cn.hutool.http.HttpUtil;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.function.BiConsumer;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

public class ZipUtils {

    /**
     * 压缩文件的获取和处理
     *
     * @param ossUrl 文件地址
     */
    public static void zipGetAndProcess(String ossUrl, BiConsumer<String, byte[]> consumer) {
        byte[] ossFileBytes = HttpUtil.downloadBytes(ossUrl);

        try (InputStream ossInput = new ByteArrayInputStream(ossFileBytes);
             ZipInputStream zipInput = new ZipInputStream(ossInput, StandardCharsets.UTF_8)) {
            ZipEntry zipEntry;
            while (null != (zipEntry = zipInput.getNextEntry())) {
                try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                    int read;
                    byte[] bytes = new byte[1024];
                    while ((read = zipInput.read(bytes)) > -1) {
                        outputStream.write(bytes, 0, read);
                    }
                    outputStream.flush();
                    // 对每个文件执行其他处理
                    consumer.accept(zipEntry.getName(), outputStream.toByteArray());
                }
            }
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        zipGetAndProcess("http://url",
                (name, bytes) -> {
                    String targetPath = "C:/Users/caoch/Desktop/" + name + ".pdf";
                    try (
                            OutputStream outputTestFile = Files.newOutputStream(Paths.get(targetPath));
                    ) {
                        // 文件测试
                        outputTestFile.write(bytes);
                        outputTestFile.flush();
                    } catch (IOException e) {
                        throw new RuntimeException(e);
                    }
                });
    }
}
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容