下面的代码显示了如何从zip归档文件解压缩和提取文件。在示例中,我们使用java.util.zip.ZipInputStream类。package org.nhooo.example.zip;
import java.io.*;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipEntry;
public class UnzipDemo {
public static void main(String[] args) {
String zipName = "data.zip";
try (FileInputStream fis = new FileInputStream(zipName);
ZipInputStream zis =
new ZipInputStream(new BufferedInputStream(fis))) {
ZipEntry entry;
// 从ZipInputStream读取每个条目,直到没有
// 发现更多条目,返回值为空
// getNextEntry()方法。
while ((entry = zis.getNextEntry()) != null) {
System.out.println("Unzipping: " + entry.getName());
int size;
byte[] buffer = new byte[2048];
try (FileOutputStream fos =
new FileOutputStream(entry.getName());
BufferedOutputStream bos =
new BufferedOutputStream(fos, buffer.length)) {
while ((size = zis.read(buffer, 0, buffer.length)) != -1) {
bos.write(buffer, 0, size);
}
bos.flush();
}
}
} catch (IOException e) {
e.printStackTrace();
}
}
}