引用:
java库学习之commons-compress实现zip包的压缩和解压_年糕coder的博客-CSDN博客
本地文件压缩zip
//path:需要压缩的文件路径地址
//返回地址为:压缩后的文件地址
public String zipFile(String path) {
int buffSize = 10 * 1024 * 1024;
String resultPath = path + ".zip";
int length;
File file = new File(path);
List<File> filesToArchive;
if (file.isDirectory()) {
filesToArchive = getAllFile(new File(path));
length= path.length();
} else {
filesToArchive = Collections.singletonList(file);
length = file.getParent().length()+1;
}
try (ArchiveOutputStream o = new ZipArchiveOutputStream(new File(resultPath))) {
for (File f : filesToArchive) {
ArchiveEntry entry = o.createArchiveEntry(f, f.getPath().substring(length));
o.putArchiveEntry(entry);
if (f.isFile()) {
try (InputStream i = Files.newInputStream(f.toPath())) {
IOUtils.copyBytes(i, o, buffSize);
}
}
o.closeArchiveEntry();
}
} catch (IOException e) {
log.error(压缩zip失败);
}
return resultPath;
}
本地zip文件解压
//path:需要解压的zip文件地址
//返回结果:解压后的文件地址
public String unzipFile(String path) {
int buffSize = 10 * 1024 * 1024;
String zipUrl = path.substring(0, path.lastIndexOf('.')) + "/";
ArchiveEntry zipEntry;
try (
FileInputStream fis = new FileInputStream(path);
BufferedInputStream bufferedInputStream = new BufferedInputStream(fis);
ZipArchiveInputStream zipInputStream = new ZipArchiveInputStream(bufferedInputStream,"GBK", true)) {
while ((zipEntry = zipInputStream.getNextEntry()) != null) {
File file = new File(zipUrl, zipEntry.getName());
if (zipEntry.isDirectory()) {
boolean mkdirs = file.mkdirs();
if (!mkdirs) {
log.error("make dir fails, dir exists Chinese");
}
} else {
FileOutputStream outPut = FileUtils.openOutputStream(file);
BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(outPut);
IOUtils.copyBytes(zipInputStream, bufferedOutputStream, buffSize);
}
}
} catch (IOException e) {
log.error("解压失败")
}
return zipUrl;
}