文件压缩zip工具
文章目录
- 文件压缩及解压缩
文件压缩及解压缩
不废话上代码
public class ZipFileUtil {
/**
* 日志记录器,用于记录ZipFileUtil类中的日志信息
*/
private static final Logger log = LoggerFactory.getLogger(ZipFileUtil.class);
/**
* 压缩多个文件成一个zip文件
*
* @param srcFiles:源文件列表
* @param destZipFile:压缩后的文件
*/
public static void toZip(List<File> srcFiles, File destZipFile) {
byte[] buf = new byte[1024];
try {
// ZipOutputStream类:完成文件或文件夹的压缩
ZipOutputStream out = new ZipOutputStream(Files.newOutputStream(destZipFile.toPath()));
for (File srcFile : srcFiles) {
FileInputStream in = new FileInputStream(srcFile);
// 给列表中的文件单独命名
out.putNextEntry(new ZipEntry(srcFile.getName()));
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.closeEntry();
in.close();
}
out.close();
} catch (Exception e) {
log.error("压缩文件失败,", e);
}
}
/**
* 解压缩指定的 ZIP 文件到指定的输出目录
*
* @param zipFile 待解压的 ZIP 文件
* @param outDir 解压后的输出目录
* @throws Exception 如果解压过程中发生错误
*/
public static void unZip(File zipFile, String outDir) throws Exception {
if (zipFile == null || !zipFile.exists() || zipFile.length() == 0) {
throw new FileNotFoundException();
}
final ZipInputStream zipInputStream = new ZipInputStream(Files.newInputStream(zipFile.toPath()));
ZipEntry entry;
while ((entry = zipInputStream.getNextEntry()) != null) {
if (!entry.isDirectory()) {
final File file = new File(outDir, entry.getName());
if (!file.exists()) {
file.getParentFile().mkdirs();
}
final FileOutputStream fileOutputStream = new FileOutputStream(file);
final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
int len;
final byte[] bytes = new byte[1024];
while ((len = zipInputStream.read(bytes)) != -1) {
bufferedOutputStream.write(bytes, 0, len);
}
bufferedOutputStream.close();
fileOutputStream.close();
}
zipInputStream.closeEntry();
}
zipInputStream.close();
}
}