该楼层疑似违规已被系统折叠 隐藏此楼查看此楼
java写的zip文件的解压缩 [雪三少 发表于 2005-12-19 16:25:23]
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.SortedSet;
import java.util.TreeSet;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
public class Unzip {
protected ZipFile zippy;
protected byte[] b;
public static void main(String[] args) {
Unzip u = new Unzip();
u.unZip("tank.zip");
}
Unzip() {
b = new byte[8092];
}
protected SortedSet dirsMade;
public void unZip(String fileName) {
dirsMade = new TreeSet();
try {
zippy = new ZipFile(fileName);
Enumeration all = zippy.entries();
while (all.hasMoreElements()) {
getFile((ZipEntry) all.nextElement());
}
} catch (IOException err) {
System.err.println("IO Error: " + err);
return;
}
}
protected boolean warnedMkDir = false;
protected void getFile(ZipEntry e) throws IOException {
String zipName = e.getName();
if (zipName.startsWith("/")) {
if (!warnedMkDir)
System.out.println("Ignoring absolute paths");
warnedMkDir = true;
zipName = zipName.substring(1);
}
if (zipName.endsWith("/")) {
return;
}
int ix = zipName.lastIndexOf('/');
if (ix > 0) {
String dirName = zipName.substring(0, ix);
if (!dirsMade.contains(dirName)) {
File d = new File(dirName);
if (!(d.exists() && d.isDirectory())) {
if (!d.mkdirs()) {
System.err.println("Warning: unable to mkdir "
+ dirName);
}
dirsMade.add(dirName);
}
}
}
FileOutputStream os = new FileOutputStream(zipName);
InputStream is = zippy.getInputStream(e);
int n = 0;
while ((n = is.read(b)) > 0) {
os.write(b, 0, n);
}
is.close();
os.close();
}
}