用以下代码将文件打成压缩包后,文件大小是0kb,因此我认为文件内容并未写入成功。却又找不到原因。麻烦各位大佬帮忙看看。
/**
* 把文件集合打成zip压缩包
*
* @param srcFiles 压缩文件集合
* @param zipFile zip文件名
* @throws RuntimeException 异常
*/
public static void toZip(List<File> srcFiles, File zipFile) throws RuntimeException {
long start = System.currentTimeMillis();
if (zipFile == null) {
log.error("压缩包文件名为空!");
return;
}
if (!zipFile.getName().endsWith(".zip")) {
log.error("压缩包文件名异常,zipFile={}", zipFile.getPath());
return;
}
ZipOutputStream zos = null;
try {
FileOutputStream out = new FileOutputStream(zipFile);
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
zos.putNextEntry(new ZipEntry(srcFile.getName()));
FileInputStream in = new FileInputStream(srcFile);
byte[] bytes = Files.readAllBytes(Paths.get(srcFile.getPath()));
zos.write(bytes, 0, bytes.length);
zos.flush();
zos.closeEntry();
in.close();
out.flush();
out.close();
}
long end = System.currentTimeMillis();
log.info("压缩完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
log.error("ZipUtil toZip exception, ", e);
throw new RuntimeException("zipFile error from ZipUtils", e);
}
}