java zip解压缩
作者:互联网
java 实现解压zip包
// An highlighted block
<!-- ZIP/RAR压缩文件解压-->
<!-- https://mvnrepository.com/artifact/ant/ant -->
<dependency>
<groupId>ant</groupId>
<artifactId>ant</artifactId>
<version>1.6.5</version>
</dependency>
package org.hwdz.common.util;
import com.alibaba.fastjson.JSONObject;
import java.io.*;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
/**
* @author : Cui mc
* @date : 2021-5-25 15:17:20
* @param //ZIP/RAR压缩文件解压
*/
public class DecompressingUtils {
public static void zipUncompress(String inputFile,String uncompress) throws Exception {
File srcFile = new File(inputFile);
// 判断源文件是否存在
if (!srcFile.exists()) {
throw new Exception(srcFile.getPath() + "所指文件不存在");
}
String destDirPath = inputFile.replace(".zip", "");
//创建压缩文件对象
ZipFile zipFile = new ZipFile(srcFile);
//开始解压
Enumeration<?> entries = zipFile.entries();
while (entries.hasMoreElements()) {
ZipEntry entry = (ZipEntry) entries.nextElement();
// 如果是文件夹,就创建个文件夹
if (entry.isDirectory()) {
srcFile.mkdirs();
} else {
// 如果是文件,就先创建一个文件,然后用io流把内容copy过去
File targetFile = new File(uncompress + "/" + 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();
}
}
}
public static void readFiles(String inputFile) throws Exception {
File srcFile = new File(inputFile);
if (srcFile.isDirectory()) {
File next[] = srcFile.listFiles();
for (int i = 0; i < next.length; i++) {
System.out.println(next[i].getName());
if(!next[i].isDirectory()){
BufferedReader br = new BufferedReader(new FileReader(next[i]));
List<String> arr1 = new ArrayList<>();
String contentLine ;
while ((contentLine = br.readLine()) != null) {
JSONObject js = JSONObject.parseObject(contentLine);
arr1.add(contentLine);
}
}
}
}
}
public static void main(String[] args) {
try {
String path = "F:\\etc\\dist(1).zip";
zipUncompress(path,"F:\\etc\\test");
readFiles(path.replace(".zip", ""));
} catch (Exception e) {
e.printStackTrace();
}
}
}
标签:java,String,zip,srcFile,解压缩,import,new 来源: https://blog.csdn.net/qq_40812553/article/details/117330581