Java 请求读取在线url的 zip压缩包中的内容 无依赖 home 编辑时间 2021/02/18 ## 前言 如题,希望用java读取一个线上地址的zip压缩包中的某个txt文件 1. 不希望下载该文件到硬盘,直接读取到流,然后在内存里完成解压缩和读取文本等所有步骤 2. 尽可能不用第三方依赖,直接用原生1.8的包来实现 ## 正文 参考 [https://blog.csdn.net/qq_32370913/article/details/110491246](https://blog.csdn.net/qq_32370913/article/details/110491246) 最终使用java8自带的 `HttpURLConnection` 和 `ZipInputStream` 来实现该功能 期间遇到一个小坑,报错如下 ```java Exception in thread "main" java.lang.IllegalArgumentException: MALFORMED at java.util.zip.ZipCoder.toString(ZipCoder.java:58) at java.util.zip.ZipInputStream.readLOC(ZipInputStream.java:300) at java.util.zip.ZipInputStream.getNextEntry(ZipInputStream.java:122) ``` 原因是编码没有使用 `GBK` ,亲测默认编码和 `UTF-8`均会报这个错误,必须是 `GBK` 或 `GB2312`,推测和压缩者的系统有关? 完整代码如下 ```java import java.io.*; import java.net.*; import java.nio.charset.Charset; import java.util.zip.*; public class Main { public static void main(String[] args) throws Throwable { String target = "http://idea.medeming.com/jets/images/jihuoma.zip"; URL url = new URL(target); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); if(conn.getResponseCode() != 200){ System.out.println("连接失败 code: " + conn.getResponseCode()); } ZipInputStream zipInputStream = new ZipInputStream(conn.getInputStream(), Charset.forName("GB2312")); ZipEntry zipEntry; while ((zipEntry = zipInputStream.getNextEntry()) != null) { String name = zipEntry.getName(); if (name.startsWith("2018") && name.endsWith("txt")) { BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(zipInputStream)); String line; while ((line = bufferedReader.readLine()) != null) { System.out.println(line); } } } } } ``` 执行结果 ```java E8V6UD5UL9-eyJsaWNlbnNlSWQiOiJFOFY2VUQ1VUw5IiwibGljZW5zZWVOYW1lIjoi5rC45LmF5r+A5rS7IGlkZWHCt21lZGVtaW5nwrdjb20iLCJhc3NpZ25lZU5hbWUiOiIiLCJhc3NpZ25lZUV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