注意:
用zipEntry.isDirectory()判断是否文件夹是,根据源代码,只能判断以 / 结尾的,不能识别以 \ 结尾的
代码如下:输入解压路径和压缩文件名(带路径的,如 D:/test.zip)
import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
/**
* author lyh
*/
public class ZIPTest1 {
public static void main(String args[]) {
ZIPTest1 zipTest1 = new ZIPTest1();
try{
zipTest1.Decompress("D:/ZipTest2/","D:/ZipTest.zip");
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 解压文件到指定目录
* @param targetPath 需要解压地址
* @param zipFilePath 压缩文件的名字(含路径 如D:/ZipTest.zip)
*/
private void Decompress(String targetPath,String zipFilePath){
File file = new File(zipFilePath);
ZipInputStream zipInputStream ;
try {
ZipFile zipFile = new ZipFile(file);
zipInputStream= new ZipInputStream(new FileInputStream(file));
ZipEntry zipEntry = zipInputStream.getNextEntry();
while(zipEntry != null){
// if (zipEntry.isDirectory()){ //这样有可能是\结尾 导致空文件夹判断不了
if (zipEntry.getName().endsWith("/") || zipEntry.getName().endsWith("\\")){
File dir = new File(targetPath +
zipEntry.getName().substring(0,zipEntry.getName().length()-1));//空文件的结尾带/
if (!dir.exists()){
dir.mkdirs();
}
}else {
DecompressFile(targetPath,zipEntry,zipFile);
}
zipInputStream.closeEntry();
zipEntry = zipInputStream.getNextEntry();
}
zipInputStream.close();
}catch (Exception e){
e.printStackTrace();
}
}
/**
* 解压单个文件(非文件夹)
* targetPath 需要解压地址
* zipFilePath 压缩文件的名字(含路径 如D:/ZipTest.zip)
*/
private void DecompressFile(String targetPath,ZipEntry zipEntry,ZipFile zipFile)throws Exception{
File tmp = new File(targetPath+zipEntry.getName());
if (!tmp.exists()){ //先判断父路径是否存在
tmp.getParentFile().mkdirs();
OutputStream outputStream = new FileOutputStream(tmp); //输出流生成新文件
InputStream inputStream = zipFile.getInputStream(zipEntry); //输入流读取Zip文件
byte bytes[]=new byte[1024];
int n=0;
while((n=inputStream.read(bytes))!= -1){
String str = new String(bytes,0,n);
outputStream.write(n);
}
outputStream.close();
inputStream.close();
}
}
}