在百度上搜了半天也没有找到一个合适的,有的不能操作文件夹,有的不能操作单个文件,有的不支持中文,总之没有找到合适的(也可能是自己搜索的能力差一些),只好自己写一个,主要代码如下:
public static void unZip(File zipFileName, File outputDirectory)
throws IOException {
File rootDir = outputDirectory;
rootDir.mkdirs();
ZipInputStream in = null;
try {
in = new ZipInputStream(new FileInputStream(zipFileName));
ZipEntry entry = in.getNextEntry();
while (entry != null) {
FileOutputStream out = null;
try {
if (!entry.isDirectory()) {
File newFile = new File(rootDir, entry.getName());
newFile.getParentFile().mkdirs();
out = new FileOutputStream(newFile);
copy(in, out);
}
entry = in.getNextEntry();
} catch (IOException io) {
io.printStackTrace();
throw io;
} finally {
out.close();
}
}
} finally {
in.close();
}
}
打包的程序:
public static void zip(File zipFile, File inputFile) throws IOException {
ZipOutputStream out = new ZipOutputStream(new FileOutputStream(zipFile));
try {
if (inputFile.isDirectory()) {
File[] fl = inputFile.listFiles();
for (int i = 0, length = fl.length; i < length; i++) {
zip(out, fl[i], "");
}
} else {
zip(out, inputFile, "");
}
} finally {
out.close();
}
}
public static void zip(ZipOutputStream out, File f, String base)
throws IOException {
// System.out.println("Zipping " + f.getName());
if (AeUtil.notNullOrEmpty(base)) {
base += "/";
}
String filePath = base + f.getName();
if (f.isDirectory()) {
File[] fl = f.listFiles();
out.putNextEntry(new JarEntry(filePath + "/"));
for (int i = 0, length = fl.length; i < length; i++) {
zip(out, fl[i], filePath);
}
} else {
out.putNextEntry(new JarEntry(filePath));
FileInputStream in = new FileInputStream(f);
try {
copy(in, out);
} catch (IOException io) {
io.printStackTrace();
throw io;
} finally {
in.close();
}
}
}
public static long copy(InputStream aIn, OutputStream aOut, int aBufferSize)
throws IOException {
byte[] buffer = new byte[aBufferSize];
int read = 0;
long totalBytes = 0;
while (-1 != (read = aIn.read(buffer))) {
aOut.write(buffer, 0, read);
totalBytes += read;
}
return totalBytes;
}
public static final int DEFAULT_BUFFER = 1024 * 4;
public static long copy(InputStream aIn, OutputStream aOut)
throws IOException {
return copy(aIn, aOut, DEFAULT_BUFFER);
}
注意中文目录的问题,要加载apache的zip包,而不能是jdk自带的