package org.jeecg.modules.dnc.utils.file;
|
|
import java.io.File;
|
import java.io.FileOutputStream;
|
import java.io.InputStream;
|
import java.nio.charset.Charset;
|
import java.util.Enumeration;
|
import java.util.zip.ZipEntry;
|
import java.util.zip.ZipFile;
|
|
/**
|
* @author clown
|
* * @date 2023/10/20
|
*/
|
public class FileZipUtil {
|
/**
|
* zip文件解压
|
* @param inputFile 待解压文件夹/文件
|
* @param destDirPath 解压路径
|
*/
|
public static void unZipFiles(String inputFile,String destDirPath) throws Exception {
|
File srcFile = new File(inputFile);//获取当前压缩文件
|
// 判断源文件是否存在
|
if (!srcFile.exists()) {
|
throw new Exception(srcFile.getPath() + "所指文件不存在");
|
}
|
ZipFile zipFile = new ZipFile(srcFile, Charset.forName("GBK"));//创建压缩文件对象
|
//开始解压
|
Enumeration<?> entries = zipFile.entries();
|
while (entries.hasMoreElements()) {
|
ZipEntry entry = (ZipEntry) entries.nextElement();
|
// 如果是文件夹,就创建个文件夹
|
if (entry.isDirectory()) {
|
String dirPath = destDirPath + "/" + entry.getName();
|
srcFile.mkdirs();
|
} else {
|
// 如果是文件,就先创建一个文件,然后用io流把内容copy过去
|
File targetFile = new File(destDirPath + "/" + entry.getName());
|
// 保证这个文件的父文件夹必须要存在
|
if (!targetFile.getParentFile().exists()) {
|
targetFile.getParentFile().mkdirs();
|
}
|
targetFile.createNewFile();
|
// 将压缩文件内容写入到这个文件中
|
InputStream is = zipFile.getInputStream(entry);
|
FileOutputStream fos = new FileOutputStream(targetFile);
|
int len;
|
byte[] buf = new byte[1024];
|
while ((len = is.read(buf)) != -1) {
|
fos.write(buf, 0, len);
|
}
|
// 关流顺序,先打开的后关闭
|
fos.close();
|
is.close();
|
}
|
}
|
}
|
|
/**
|
* 删除文件
|
*
|
* @param filePath
|
* @return
|
*/
|
public static boolean deleteFile(String filePath) {
|
boolean flag = false;
|
File file = new File(filePath);
|
if (!file.exists()) {
|
return flag;
|
}
|
if (!file.isDirectory()) {
|
return flag;
|
}
|
String[] tempList = file.list();
|
File temp;
|
for (int i = 0; i < tempList.length; i++) {
|
if (filePath.endsWith(File.separator)) {
|
temp = new File(filePath + tempList[i]);
|
} else {
|
temp = new File(filePath + File.separator + tempList[i]);
|
}
|
if (temp.isFile()) {
|
temp.delete();
|
}
|
if (temp.isDirectory()) {
|
// 先删除文件夹里面的文件
|
deleteFile(filePath + "/" + tempList[i]);
|
// 再删除空文件夹
|
deleteFile(filePath + "/" + tempList[i]);
|
flag = true;
|
}
|
}
|
return flag;
|
}
|
}
|