zip 文件解压
亲测有效
长相思兮长相忆,短相思兮无穷极。
这里没有做异常抛出,自己去try吧
package com.example.demo.test;
import lombok.SneakyThrows;
import java.io.*;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* Zip解压
*
* @Author yls
* @Date 2021/7/15 9:44
* @Version 1.0
*/
public class ZipTest {
public static void main(String[] args) {
try {
unZipFiles("D:\\OneDrive\\master.zip","C:\\Users\\22069\\OneDrive\\");
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* zip解压工具类
*
* @param zipFilePath 要解压的源文件
* @param descDir 解压到哪个文件夹下?
* @throws IOException
*/
public static void unZipFiles(String zipFilePath, String descDir) throws IOException {
File zipFile = new File(zipFilePath);
//判断是否存在要解压的文件
if (zipFile.exists()) {
System.out.println("zip源文件不存在");
return;
}
File pathFile = new File(descDir);
if (!pathFile.exists()) {
//按照解压路径去创建文件夹
pathFile.mkdirs();
}
//设置编码格式,解决zip文件中有中文目录或者中文文件乱码
ZipFile zip = new ZipFile(zipFile, Charset.forName("UTF-8"));
for (Enumeration entries = zip.entries(); entries.hasMoreElements(); ) {
ZipEntry entry = (ZipEntry) entries.nextElement();
String zipEntryName = entry.getName();
InputStream in = zip.getInputStream(entry);
String outPath = (descDir + zipEntryName).replaceAll("\\*", "/");
//在解压过程中判断文件目录是否存在在,不存在则创建文件路径
File file = new File(outPath.substring(0, outPath.lastIndexOf('/')));
if (!file.exists()) {
file.mkdirs();
}
//判断文件全路径是否为文件夹,如果是上面已经上传,不需要解压
if (new File(outPath).isDirectory()) {
continue;
}
//输出加压的文件路径信息
System.out.println(outPath);
OutputStream out = new FileOutputStream(outPath);
byte[] buf1 = new byte[1024];
int len;
while ((len = in.read(buf1)) > 0) {
out.write(buf1, 0, len);
}
in.close();
out.close();
}
System.out.println("----------------解压完犊子了------------");
}
}
如果您感觉这个解压有问题,现在有一个开源的jar去解压,非常方便,那就是在maven里面去引入
<dependency>
<groupId>net.lingala.zip4j</groupId>
<artifactId>zip4j</artifactId>
<version>1.3.2</version>
</dependency>
然后就可以开始了
-------->
/**
* yss
* 解压缩文件(带密码)
* */
public class UncompressZipUtil {
/**
*带密解压
* @param sourceFile 要解压的文件(C:\other\ima.zip)
* @param destPath 解压存放的目录
* @param password 解压密码 (文件需要密码时传参,不需要时随意)
*/
private static void openZip(String sourceFile,String destPath,String password) {
try {
ZipFile zipFile = new ZipFile(sourceFile);
zipFile.setFileNameCharset("GBK");
// 如果解压需要密码
if(zipFile.isEncrypted()) {
zipFile.setPassword(password);
}
zipFile.extractAll(destPath);
} catch (ZipException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
unzip("C:\\Users\\22069\\OneDrive\\桌面\\bj.zip","C:\\Users\\22069\\OneDrive\\桌面\\新建文件夹\\","");
}
}
亲测有效,非常nice!!!