public void testReadZip() throws Exception {
// InputStream is=new BufferedInputStream(new FileInputStream());
String baseDir = "C://Documents and Settings//ws//桌面//新建文件夹";
ZipFile zfile = new ZipFile("C://Documents and Settings//ws//桌面//新建文件夹//dd.zip");
System.out.println(zfile.getName());
Enumeration zList = zfile.entries();
ZipEntry ze = null;
byte[] buf = new byte[1024];
while (zList.hasMoreElements()) {
// 从ZipFile中得到一个ZipEntry
ze = (ZipEntry) zList.nextElement();
if (ze.isDirectory()) {
System.out.println("Dir: " + ze.getName() + " skipped..");
continue;
}
System.out.println("Extracting: " + ze.getName() + "/t"
+ ze.getSize() + "/t" + ze.getCompressedSize());
// 以ZipEntry为参数得到一个InputStream,并写到OutputStream中
OutputStream os = new BufferedOutputStream(new FileOutputStream(
getRealFileName(baseDir, ze.getName())));
InputStream is = new BufferedInputStream(zfile.getInputStream(ze));
int readLen = 0;
while ((readLen = is.read(buf, 0, 1024)) != -1) {
os.write(buf, 0, readLen);
}
is.close();
os.close();
System.out.println("Extracted: " + ze.getName());
}
zfile.close();
}
private File getRealFileName(String baseDir, String absFileName) {//指定根目录// 相对路径名——ZipEntry中的name
String[] dirs = absFileName.split("/");
// System.out.println(dirs.length);
File ret = new File(baseDir);
if (dirs.length > 1) {
for (int i = 0; i < dirs.length - 1; i++) {
ret = new File(ret, dirs[i]);
}
}
if (!ret.exists()) {
ret.mkdirs();
}
ret = new File(ret, dirs[dirs.length - 1]);
return ret;
}
Java 解压文件
最新推荐文章于 2024-07-29 14:22:26 发布