/**
* 解压到指定目录
*
* @param zipPath 待解压的zip文件
* @param descDir 指定目录
*/
public void unZipFiles(String zipPath, String descDir) {
unZipFiles(new File(zipPath), descDir);
}
/**
* 解压文件到指定目录
* 解压后的文件名,和之前一致
*
* @param zipFile 待解压的zip文件
* @param descDir 指定目录
*/
public void unZipFiles(File zipFile, String descDir) {
try (ZipFile zip = new ZipFile(zipFile, Charset.forName("GBK"));) {
String name = zip.getName().substring(zip.getName().lastIndexOf('/') + 1, zip.getName().lastIndexOf('.'));
File pathFile = new File(descDir + name);
if (!pathFile.exists()) {
pathFile.mkdirs();
}
for (Enumeration<? extends ZipEntry> entries = zip.entries(); entries.hasMoreElements(); ) {
ZipEntry entry = entries.nextElement();
String zipEntryName = entry.getName();
try (InputStream in = zip.getInputStream(entry);) {
String outPath = (descDir + name + "/" + zipEntryName).replaceAll("\\*", "/");
// 判断路径是否存在,不存在则创建文件路径
File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if (!file.exists()) {
file.mkdirs();
}
// 判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
if (new File(outPath).isDirectory()) {
continue;
}
try (FileOutputStream out = new FileOutputStream(outPath);) {
byte[] buf1 = new byte[1024];
int len;
while ((len = in.read(buf1)) > 0) {
out.write(buf1, 0, len);
}
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
} catch (IOException e) {
throw new RuntimeException(e);
}
}
/**
* 把目录下的所有文件移动到指定文件夹
* @param sourceDir 源文件夹
* @param source 指定文件夹
*/
private void moveFiles(File sourceDir, File source) {
File[] files = sourceDir.listFiles();
if (files != null) {
for (File file : files) {
if (file.isDirectory()) {
moveFiles(file, source);
// 检查文件夹是否为空
if (file.list().length == 0) {
file.delete();
}
} else {
try {
Files.move(file.toPath(), Paths.get(source.toString() , file.getName()) , StandardCopyOption.REPLACE_EXISTING);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
}
}
调用的代码,先解压到指定文件夹,删除压缩包,然后把这个文件夹的所有文件都提取到这个文件夹根目录下,删除空目录
if (fileName != null && fileName.endsWith(".zip")) {
// 处理ZIP文件
Path zipFile = Paths.get(filePathStr);
Path parentDir = zipFile.getParent(); // zip 所在目录
this.unZipFiles(filePathStr, "");
Files.delete(Paths.get(filePathStr));
this.moveFiles(parentDir.toFile(), parentDir.toFile());
}