1.编写 工具类 ZipUtil
package com.susoft.utils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.util.Enumeration;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
public class ZipUtils {
private static final Logger logger = LoggerFactory.getLogger(ZipUtils.class);
private ZipUtils(){
// 私用构造主法.因为此类是工具类.
}
/**
* 解压zip文件
*
* @param zipFileName
* 待解压的zip文件路径,例如:c:\a.zip
*
* @param outputDirectory
* 解压目标文件夹,例如:c:\a
*/
public static void unZip(String zipFileName, String outputDirectory)
throws Exception {
logger.debug("开始解压 ["+zipFileName+"] 到 ["+outputDirectory+"]");
org.apache.tools.zip.ZipFile zipFile = new org.apache.tools.zip.ZipFile(zipFileName);
try {
Enumeration<?> e = zipFile.getEntries();
org.apache.tools.zip.ZipEntry zipEntry = null;
createDirectory(outputDirectory, "");
while (e.hasMoreElements()) {
zipEntry = (org.apache.tools.zip.ZipEntry) e.nextElement();
logger.debug("解压:" + zipEntry.getName());
if (zipEntry.isDirectory()) {
String name = zipEntry.getName();
name = name.substring(0, name.length() - 1);
File f = new File(outputDirectory + File.separator + name);
f.mkdir();
logger.debug("创建目录:" + outputDirectory + File.separator + name);
} else {
String fileName = zipEntry.getName();
fileName = fileName.replace('\', '/');
if (fileName.indexOf("/") != -1) {
createDirectory(outputDirectory, fileName.substring(0,
fileName.lastIndexOf("/")));
fileName = fileName.substring(
fileName.lastIndexOf("/") + 1,
fileName.length());
}
File f = new File(outputDirectory + File.separator
+ zipEntry.getName());
f.createNewFile();
InputStream in = zipFile.getInputStream(zipEntry);
FileOutputStream out = new FileOutputStream(f);
byte[] by = new byte[1024];
int c;
while ((c = in.read(by)) != -1) {
out.write(by, 0, c);
}
in.close();
out.close();
}
}
logger.debug("解压 ["+zipFileName+"] 完成!");
} catch (Exception ex) {
System.out.println(ex.getMessage());
} finally {
zipFile.close();
}
}
/**
* 创建目录
* @author hezhao
* @Time 2017年7月28日 下午7:10:05
* @param directory
* @param subDirectory
*/
private static void createDirectory(String directory, String subDirectory) {
String dir[];
File fl = new File(directory);
try {
if (subDirectory == "" && fl.exists() != true) {
fl.mkdir();
} else if (subDirectory != "") {
dir = subDirectory.replace('\', '/').split("/");
for (int i = 0; i < dir.length; i++) {
File subFile = new File(directory + File.separator + dir[i]);
if (subFile.exists() == false)
subFile.mkdir();
directory += File.separator + dir[i];
}
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
}
编写测试类
import org.junit.Test;
public class BeanTest {
@Test
public void test() {
ZipUtils zp = new ZipUtils ();
zo.unZip(xxx,yyy);
}