package leetcode.editor.cn;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.Scanner;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* @author Dkui
* @version 1.0.0
* @ClassName fileZip.java
* @Description TODO
* @createTime 2021年11月12日 17:01:00
*/
public class fileZip {
/**
* 指定解压单个文件(可循环调用)
*
* @param zipFile 解压的文件路径含文件本身
* @param descDir 解压到某个路径
* @Author Maiza
*/
public static void unZipFile(File zipFile, String descDir) {
File pathFile = new File(descDir);
OutputStream out = null;
InputStream in = null;
ZipFile zip = null;
try {
if (!pathFile.exists()) {
pathFile.mkdirs();
}
//设置处理压缩包语言
zip = new ZipFile(zipFile, Charset.forName("UTF-8"));
//开始循环解压缩
for (Enumeration entries = zip.entries(); entries.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String zipEntryName = entry.getName();
in = zip.getInputStream(entry);
String outPath = descDir + "\\" + zipEntryName;
out = new FileOutputStream(outPath);
byte[] buf1 = new byte[1024];
int len;
while ((len = in.read(buf1)) > 0) {
out.write(buf1, 0, len);
}
//每次循环关闭一次流,避免资源泄露.如果不关闭,系统将一直占用资源.
out.close();
in.close();
}
} catch (Exception e) {
} finally {
try {
out.close();
in.close();
zip.close();
} catch (Exception e) {
}
}
}
public static void showDir(File dir, String pat) {
if (dir.exists()) {
//抽象路径名数组,这些路径名表示此抽象路径名表示的目录中的文件和目录。
File[] files = dir.listFiles();
int count = count(pat);
if (null != files) {
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
showDir(files[i]);
} else {
System.out.println(files[i]);
// 获取名称
String name = getName(files[i], count);
unZipFile(files[i], pat + "\\" + name);
}
}
}
} else {
System.out.println("文件不存在!");
}
}
private static void showDir(File file) {
}
private static int count(String file) {
String[] phats = file.split("\\\\");
return phats.length;
}
private static String getName(File file, int count) {
String fil = file.toString();
String[] phats = fil.split("\\\\");
String zipName = phats[count];
String[] name = zipName.split(".zip");
return name[0];
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入要解压zip的文件夹地址:");
String path = sc.nextLine();
showDir(new File(path), path);
}
}
批量解压某文件夹下的.zip文件并生成对应文件夹名
最新推荐文章于 2024-08-17 22:35:31 发布