简单的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);
}
});
}
}