转载自:https://springboot.io/t/topic/626
叙述
业务中需要将几个文件压缩为一个包,有以下解决方案。
代码
/**
@param files 需要被压缩的文件
@param zipFile 压缩后的目标zip文件
*/
public static void zip(Path[] files, Path zipFile) throws IOException {
OutputStream outputStream = Files.newOutputStream(zipFile, StandardOpenOption.CREATE_NEW);
ZipOutputStream zipOutputStream = new ZipOutputStream(outputStream);
for (Path file : files) {
InputStream inputStream = Files.newInputStream(file);
zipOutputStream.putNextEntry(new ZipEntry(file.getFileName().toString()));
int len;
byte[] buffer = new byte[1024 * 10];
while ((len = inputStream.read(buffer)) > 0) {
zipOutputStream.write(buffer, 0, len);
}
inputStream.close();
}
zipOutputStream.closeEntry();
zipOutputStream.close();
outputStream.close();
}