import java.io.*;
import org.apache.tools.zip.*;
import java.util.*;
public class FileUtil {
/**
* 将一个目录压缩,自动加上后缀zip
* 生成的zip文件与原目录在同一根目录下面
* @param sourcePath String
*/
static public void zipDirectory(String sourcePath) {
try {
File f = new File(sourcePath);
String destFilePath = f.getPath() + ".zip";
ZipOutputStream out = new ZipOutputStream(new File(destFilePath));
zipDirectory(out, f, f.getParent());
out.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
static private void zipDirectory(ZipOutputStream out,
File f, String rootDir) {
try {
if (f.isDirectory()) {
File[] subDir = f.listFiles();
for (int i = 0; i < subDir.length; i++) {
zipDirectory(out, subDir[i], rootDir);
}
}
else {
System.out.println("Adding: " + f.getPath());
byte data[] = new byte[1024];
String entryName = f.getPath().substring(rootDir.length() + 1);
FileInputStream in = new FileInputStream(f);
ZipEntry entry = new ZipEntry(entryName);
out.putNextEntry(entry);
int count;
while ( (count = in.read(data, 0, data.length)) != -1) {
out.write(data, 0, count);
}
in.close();
}
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* 解压一个zip文件,生成的新目录与原zip文件在同一根目录下面
* @param zipfilename String
*/
public static void unzipDirectory(String zipfilename) {
byte[] buf = new byte[1024];
try {
File rootFile = new File(zipfilename).getParentFile();
ZipFile src = new ZipFile(zipfilename);
Enumeration enume = src.getEntries();
while (enume.hasMoreElements()) {
ZipEntry entry = (ZipEntry) enume.nextElement();
if(entry.isDirectory()) {
continue;
}
String entryName = entry.getName();
File f = new File(rootFile, entryName);
File parentDir = f.getParentFile();
if (parentDir.exists() == false) {
parentDir.mkdirs();
}
System.out.println("Unzip: " + f.getPath());
BufferedInputStream in = new BufferedInputStream(src.
getInputStream(entry));
BufferedOutputStream out = new BufferedOutputStream(new
FileOutputStream(f));
int count;
while ( (count = in.read(buf)) != -1) {
out.write(buf, 0, count);
}
out.close();
in.close();
}
src.close();
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}

没有排序,也不用再加入目录的信息,也可解压其他软件打包的zip文件!