解压文件简易教程
回头巩固自己的java基础知识
可以这两个大佬的参考两个网址
https://www.cnblogs.com/zeng1994/p/8142862.html
https://blog.csdn.net/lnniyunlong99/article/details/59548121
具体步骤
1、准备
(1)idear一类的编辑工具
(2)两个url(地址路径),一个是zip(压缩包)的路径,另外一个zip是要解压的位置
2.工具类代码块
public class ZipsUtil{
//解压压缩包到指定位置
public boolean PlaceZip(String btainUrl, String storageUrl) {
//开始时间
Long start = System.currentTimeMillis();
//确认存放的文件路径存在
File file = new File(storageUrl);
if (!new File(btainUrl).exists()) {
System.out.println("文件不存在");
return false;
}
//获取存放文件名
String FileName = file.getName();
ZipFile zipFile = null;
try {
//大部分的压缩包编码格式是GBK
zipFile = new ZipFile(new File(btainUrl), Charset.forName("GBK"));
//枚举
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
//获取到压缩包
ZipEntry entry = (ZipEntry) entries.nextElement();
System.out.println("解压" + entry.getName());
//判断是否有文件夹
if (entry.isDirectory()) {
//如果有,就创建
File dir = new File(FileName + "/" + entry.getName());
dir.mkdir();
} else {
//解压路径+文件名
String str = storageUrl + "/" + entry.getName();
File targetFile = new File(str);
//判断文件是否存在
if (!targetFile.getParentFile().exists()) {
//创建文件
targetFile.getParentFile().mkdir();
}
//创建文件
boolean newFile = targetFile.createNewFile();
if (!newFile) {
System.out.println("创建文件失败");
}
//字节流读取写入
InputStream in = zipFile.getInputStream(entry);
OutputStream out = new FileOutputStream(targetFile);
int len = 0;
while ((len = in.read()) != -1) {
out.write(len);
out.flush();
}
//关闭io流;
in.close();
out.close();
}
}
//结束时间
long end = System.currentTimeMillis();
System.out.println("解压耗时" + (end - start) + "ms");
return true;
} catch (Exception e) {
e.printStackTrace();
} finally {
if (zipFile != null) {
try {
//关闭压缩文件
zipFile.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return false;
}
}
3、接下里只需要main方法调用就行
public class Test5{
public static void main(String[] args){
String url1="C:\\Users\\MAZ\\Desktop\\哈哈哈.zip";
String url2="C:\\Users\\MAZ\\Desktop\\";
ZipsUtil zipsUtil =new ZipsUtil();
boolean b1 = zipsUtil.PlaceZip(url1, url2);
if(b1){
System.out.println("解压成功");
}
}
}
3、结束语
谢谢观看,多加理解,渐入佳境。