(这里有个中文路径的问题没有解决)
package qimiguang.test;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.io.BufferedInputStream;
public class Test {
static final int BUFFER = 2048;
public static void main(String argv[]) {
String zipFilePath = "E:\\new\\log 2013-09-23 14_56_57.zip";// 要解压的压缩文件的存放路径
String targetPath = "E:\\b\\";// /解压到的目标文件路径
unZip(zipFilePath, targetPath);
}
/**
*
* @param zipFilePath 要解压的zip压缩包的路径
* @param targetPath 解压到的目标文件夹路径
*/
public static void unZip(String zipFilePath, String targetPath) {
BufferedOutputStream bos = null;
FileInputStream fis = null;
ZipInputStream zis = null;
try {
fis = new FileInputStream(zipFilePath);
zis = new ZipInputStream(new BufferedInputStream(fis));
ZipEntry entry;
while ((entry = zis.getNextEntry()) != null) {
int count;
byte data[] = new byte[BUFFER];
if (entry.isDirectory()) {
continue;
}
bos = new BufferedOutputStream(new FileOutputStream(
buildRealFile(targetPath, entry.getName())));
while ((count = zis.read(data, 0, BUFFER)) != -1) {
bos.write(data, 0, count);
}
bos.flush();
bos.close(); // 注意流一定要在这里关!!!
}
zis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if(bos != null) {
bos.close();
}
if(fis != null) {
fis.close();
}
if(zis != null) {
zis.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 给定根目录,返回一个相对路径所对应的实际文件名.
*
* @param rootName 解压缩后文件存放的根目录
* @param relativeFileName 相对路径名,来自于ZipEntry中的name
* @return java.io.File 实际的文件
*/
public static File buildRealFile(String rootName, String relativeFileName) {
String[] dirs = relativeFileName.split("/", relativeFileName.length());
File file = new File(rootName);
if (dirs.length > 1) {
for (int i = 0; i < dirs.length - 1; i++) {
file = new File(file, dirs[i]);
}
}
if (!file.exists()) {
file.mkdirs();
}
file = new File(file, dirs[dirs.length - 1]);
return file;
}
}