public class ZipTest {
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());
}
}
public static void unZip(String zipFileName, String outputDirectory) throws Exception {
try {
org.apache.tools.zip.ZipFile zipFile = new org.apache.tools.zip.ZipFile(zipFileName);
java.util.Enumeration e = zipFile.getEntries();
org.apache.tools.zip.ZipEntry zipEntry = null;
createDirectory(outputDirectory, "");
while (e.hasMoreElements()) {
zipEntry = (org.apache.tools.zip.ZipEntry) e.nextElement();
System.out.println("unziping " + 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();
System.out.println("创建目录:" + 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);
}
out.close();
in.close();
}
}
}
catch (Exception ex) {
System.out.println(ex.getMessage());
}
}
public static void main(String[] args) {
//ZipTest.unZip("d:\\export.zip", "d:\\file", 1);
try {
ZipTest.unZip("d:\\test.zip", "d:\\");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("this is test!!!");
}
}
1.因为ZipOutputStream压缩和解压ZIP文件对文件名都是以UTF-8编码方式来处理的,而WinZip对文件名只会以ASCII编码方式来处理。所以他们之间会产生冲突:WinZip解压Java产生的压缩文件时文件名乱码;Java解压WinZip产生的压缩文件时出现异常。
解决办法:Apache Ant有个包专门处理ZIP文件,可以指定文件名的编码方式。由此可以解决问题。
ant.jar (1.70) 测试通过
------君临天下,舍我其谁
------