使用java.util.zip实现文件压缩
public static void toZip(File[] srcFiles, OutputStream out){
long start = System.currentTimeMillis();
ZipOutputStream zos = null;
try {
zos = new ZipOutputStream(out);
for (File srcFile : srcFiles) {
byte[] buf = new byte[BUFFER_SIZE];
zos.putNextEntry(new ZipEntry(srcFile.getName()));
int len;
FileInputStream in = new FileInputStream(srcFile);
while ((len = in.read(buf)) != -1) {
zos.write(buf, 0, len);
}
zos.closeEntry();
zos.flush();
in.close();
}
long end = System.currentTimeMillis();
log.debug("压缩完成,耗时:" + (end - start) + " ms");
} catch (Exception e) {
e.printStackTrace();
log.error("系统异常:",e);
} finally {
if (zos != null) {
try {
zos.close();
} catch (IOException e) {
e.printStackTrace();
log.error("系统异常:",e);
}
}
}
}