pom:
<!-- https://mvnrepository.com/artifact/org.apache.commons/commons-compress -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-compress</artifactId>
<version>1.27.1</version>
</dependency>
解压:
/**
* 解压zip文件
* @param destDir
* @param inputStream
*/
public void unCompress(String destDir,InputStream inputStream,String type){
//1.采用jdk原生Zip流,会因为发送方和接收方,在处理文件或文件夹名称时用的【字符集编码】不匹配,而报MALFORMED错(畸形的)
//ZipInputStream zipInputStream = new ZipInputStream(inputStream);
//2.Apach-commons-compress的Zip流,兼容性更好
try (ArchiveInputStream archiveInputStream = new ArchiveStreamFactory().createArchiveInputStream(type,inputStream)) {
byte[] buffer = new byte[4096];
ArchiveEntry zipEntry;
while ((zipEntry = archiveInputStream.getNextEntry()) != null) {
String entryFileName = zipEntry.getName();
File outputDir = new File(destDir);
File outputFile = new File(outputDir, entryFileName);
if (zipEntry.isDirectory()) {
if (!outputFile.exists()) {
outputFile.mkdirs();
}
} else {
File parent = outputFile.getParentFile();
if (!parent.exists()) {
parent.mkdirs();
}
// Write the extracted file to disk
try (FileOutputStream fos = new FileOutputStream(outputFile)) {
int length;
while ((length = archiveInputStream.read(buffer)) > 0) {
fos.write(buffer, 0, length);
}
}
}
}
} catch (IOException e) {
log.error("解压文件失败",e);
} catch (ArchiveException e) {
throw new RuntimeException(e);
}
}
压缩:
将不同文件通过archiveOutputStream.putArchiveEntry 添加合并
public void compress(File file, ArchiveOutputStream archiveOutputStream,String curPath) throws Exception {
if(!file.exists()){
throw new RuntimeException("文件"+file.getName()+"不存在");
}
if (file.isDirectory()) {
File[] files = file.listFiles();
if (files != null && files.length > 0) {
for (File f : files) {
compress(f, archiveOutputStream, curPath+file.getName() + "/");
}
}
} else {
archiveOutputStream.putArchiveEntry(new ZipArchiveEntry(curPath + file.getName()));
try (FileInputStream fis = new FileInputStream(file)){
byte[] buffer = new byte[1024];
int length;
while ((length = fis.read(buffer)) > 0) {
archiveOutputStream.write(buffer, 0, length);
}
archiveOutputStream.closeArchiveEntry();
}
}
}
public void compress(File file,String type, OutputStream outputStream) {
try (ArchiveOutputStream archiveOutputStream = new ArchiveStreamFactory().createArchiveOutputStream(type,outputStream)) {
compress(file, archiveOutputStream,"");
}catch (Exception e){
log.error("压缩文件失败",e);
throw new RuntimeException(e);
}
}
参考:


被折叠的 条评论
为什么被折叠?



