public class ReadZipFile {
private static void mkdir(File file) {
if (!file.exists())
file.mkdir();
else if (!file.isDirectory()) {
throw new RuntimeException(String.format("因为%s已经存在,且不是目录,所以%<s目录无法创建", file.getPath()));
}
}
public static void main(String args[]) throws FileNotFoundException, IOException {
File contextpath = new File("mybook");
mkdir(contextpath);
byte b[] = new byte[8 * 1024];
try (ZipInputStream zipin = new ZipInputStream(ReadZipFile.class.getResourceAsStream("book.zip"),
Charset.forName("gbk"));) {
ZipEntry zipEntry = null;
while ((zipEntry = zipin.getNextEntry()) != null) {
File item = new File(contextpath, zipEntry.getName());
if (zipEntry.isDirectory()) {
System.out.println("创建了目录"+item.getAbsolutePath());
mkdir(item);
} else {
try (FileOutputStream out = new FileOutputStream(item);) {
int n = -1;
System.out.println("创建了文件"+item.getAbsolutePath());
while ((n = zipin.read(b, 0, b.length)) != -1) {
out.write(b, 0, n);
}
}
try (FileInputStream in = new FileInputStream(item);){
byte[] allbytes = new byte[(int) item.length()];
in.read(allbytes);
System.out.println(new String(allbytes));
}
}
}
}
}
}