java实现zip文件的解压 java解压压缩包到指定文件夹
一、导入相关依赖包
<dependency>
<groupId>org.apache.ant</groupId>
<artifactId>ant</artifactId>
<version>1.8.1</version>
</dependency>
二、创建相应的工具类
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import com.xxx.xxx.entity.xxx.WkcrWord;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
/**
* 解压文件的工具类
*/
public class ZipUtil {
/**
* 解压文件
* @param directory 文件目录
* @param zip 文件zip的压缩包
*/
public static List<WkcrWord> unZipFile(String directory, File zip) {
List<WkcrWord> filePathList=new ArrayList<>();
try {
int count;
int buffer = 2048;
File file;
InputStream is;
FileOutputStream fos;
BufferedOutputStream bos;
//根据不同环境,不同的文件,需要使用到不同的编码格式
ZipFile zipFile = new ZipFile(zip, "GBK");
Enumeration en = zipFile.getEntries();
createFolder(directory);
while (en.hasMoreElements()) {
byte buf[] = new byte[buffer];
ZipEntry entry = (ZipEntry) en.nextElement();
//获取压缩包中的文件的名字
String fileName = entry.getName();
if(fileName.contains("/")){
fileName=fileName.substring(fileName.lastIndexOf("/")+1);
}
String filePath = directory + fileName;
//根据业务逻辑创建相应的实体类
WkcrWord wkcrWord=new WkcrWord();
wkcrWord.setName(fileName);
wkcrWord.setWordUrl(filePath);
//根据不同的文件后缀设置正则表达式
String compile = ".*.doc.*|.*.docx.*";
//符合的保存
if(filePath.matches(compile)){
filePathList.add(wkcrWord);
}
if(entry.isDirectory()){
createFolder(filePath);
}else{
file = new File(filePath);
file.createNewFile();
is = zipFile.getInputStream(entry);
fos = new FileOutputStream(file);
bos = new BufferedOutputStream(fos, buffer);
while ((count = is.read(buf)) > -1) {
bos.write(buf, 0, count);
}
bos.close();
fos.close();
is.close();
}
}
zipFile.close();
//遍历当前上传的word进行转化为html进行相应的保存
filePathList.stream().forEach(wkcrWord-> wkcrWord.setWordTxt(DocTableReadUtil.saveWord(wkcrWord.getWordUrl(),wkcrWord.getName())));
} catch (IOException e) {
e.printStackTrace();
}finally {
zip.delete();
}
return filePathList;
}
/**
* 创建目录
* @param path 文件的目录
*/
private static void createFolder(String path) {
try {
File uploadFilePath = new File(path);
if (uploadFilePath.exists() == false) {
uploadFilePath.mkdirs();
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}