下面的代码可以解压包含目录的ZIP文件.需要先去http://ant.apache.org/ivy/download.cgi下载 Apache Ant,并导入其中的ant.jar.
package com.test;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipFile;
public class T
{
/*
* 下载Apache Ant http://ant.apache.org/ivy/download.cgi 导入其中的ant.jar
*/
public static void main(String[] args) throws IOException
{
// TODO Auto-generated method stub
ZipFile zf = new ZipFile("D:/adf.zip");
// ZIP文件
String outDir = "D:/";
// 输出路径
Enumeration entries = zf.getEntries();
while (entries.hasMoreElements())
{
ZipEntry entry = (ZipEntry) entries.nextElement();
System.out.println(entry.getName());
File f = new File(outDir + entry.getName());
if (entry.isDirectory())
{
continue;
}
File parent = f.getParentFile();
if (!parent.exists())
{
parent.mkdirs();
//这里就会创建该文件所有的上级目录,所以上面isDirectory()不执行,直接continue
}
InputStream is = zf.getInputStream(entry);
FileOutputStream fop = new FileOutputStream(outDir + entry.getName());
int len = 0;
byte[] bs = new byte[1024];
while ((len = is.read(bs, 0, 1024)) > 0)
{
fop.write(bs, 0, len);
}
is.close();
fop.close();
}
}
}