JAVA压缩与解压缩ZIP文件



JAVA压缩与解压缩ZIP文件

1、压缩文件代码
将sourceDir文件夹下的文件压缩成zipFile的ZIP包。

public static void zip(String sourceDir, String zipFile) {
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(zipFile));
ZipOutputStream zos = new ZipOutputStream(bos);
File file = new File(sourceDir);
String basePath = null;
if (file.isDirectory()) {
basePath = file.getPath();
} else {
basePath = file.getParent();
}
zipFile(file, basePath, zos);
zos.closeEntry();
zos.close();
} catch (Exception e) {

}
}

//辅助函数,压缩文件
private static void zipFile(File source, String basePath, ZipOutputStream zos) {
File[] files = new File[0];
if (source.isDirectory()) {
files = source.listFiles();
} else {
files = new File[1];
files[0] = source;
}
String pathName;
byte[] buf = new byte[1024];
int length = 0;
try {
for (int i = 0; i < files.length; i++) {
File file = files[i];
if (file.isDirectory()) {
pathName = file.getPath().substring(basePath.length() + 1) + “/”;
zos.putNextEntry(new ZipEntry(pathName));
zipFile(file, basePath, zos);
} else {
pathName = file.getPath().substring(basePath.length() + 1);
InputStream is = new FileInputStream(file);
BufferedInputStream bis = new BufferedInputStream(is);
zos.putNextEntry(new ZipEntry(pathName));
while ((length = bis.read(buf)) > 0) {
zos.write(buf, 0, length);
}
is.close();
bis.close();
}
}
} catch (Exception e) {
}
}

2、解压缩ZIP文件
将zipfile文件解压到destDir目录下

public static void unZip(String zipfile, String destDir) {
destDir = destDir.endsWith(“\\”) ? destDir : destDir + “\\”;
byte b[] = new byte[1024];
int length;
ZipFile zipFile;
try {
zipFile = new ZipFile(new File(zipfile));
Enumeration enumeration = zipFile.getEntries();
ZipEntry zipEntry = null;
while (enumeration.hasMoreElements()) {
zipEntry = (ZipEntry) enumeration.nextElement();
File loadFile = new File(destDir + zipEntry.getName());
if (zipEntry.isDirectory()) {
loadFile.mkdirs();
} else {
if (!loadFile.getParentFile().exists())
loadFile.getParentFile().mkdirs();
OutputStream outputStream = new FileOutputStream(loadFile);
InputStream inputStream = zipFile.getInputStream(zipEntry);
while ((length = inputStream.read(b)) > 0){
outputStream.write(b, 0, length);
}
outputStream.close();
inputStream.close();
}
}
} catch (IOException e) {

}
}

3、主函数,测试用
public static void main(String[] args) {
zip(“D:\\新建文件夹”, “D:\\123.zip “);
unZip(“D:\\123.zip”, “D:\\”);
}