ZIP文档(通常)以压缩格式存储了一个或多个文件,每个ZIP文档都有一个包含诸如文件名字和使用的压缩方法等信息的头。
(1)使用ZIPInputStream来读入ZIP,通过getNextEntry方法返回一个描述这些项的ZipEntry类型的对象。
ZIPInputStream的read方法被修改为在碰到当前项的结尾时返回 -1 ,必须通过调用closeEntry来读下一项。
e.g.通读ZIP文件的代码序列 ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry entry = null;
while((entry=zin.getNextEntry()) != null){
... ...
zin.closeEntry();
}
zin.close();
(2)可以不使用原生的read方法,通常会使用某个更能胜任的流过滤器的方法。
e.g.读ZIP文件内部的一个文本文件
ZipInputStream zin = new ZipInputStream(new FileInputStream(zipFile));
ZipEntry entry = null;
Scanner in = null;
while((entry=zin.getNextEntry()) != null){
in = new Scanner(zin);
while(in.hasNextLine()){
System.out.println(in.nextLine());
}
zin.closeEntry();
}
in.close();
注意:如果压缩文件被损坏会抛出ZipException
(3)写出到ZIP文件,可以使用ZipOutputStream
对于ZIP中每一项都应创建一个ZipEntry对象,并将文件名传递给ZipEntry的构造器,它将设置文件日期和解压方法等参数。如果需要也可以覆盖这些设置。
然后调用ZipOutputStream的putNextEntry方法来开始写新文件,并将文件数据发送到ZIP流中。完成后调用closeEntry。
private static void testZIP() {
try{
File fromFile1 = new File(System.getProperty("user.dir")+"\\Notes\\流\\zip\\1.txt");
File fromFile2 = new File(System.getProperty("user.dir")+"\\Notes\\流\\zip\\2.txt");
DataInputStream in1 = new DataInputStream(new BufferedInputStream(new FileInputStream(fromFile1)));
DataInputStream in2 = new DataInputStream(new FileInputStream(fromFile2));
File toFile = new File(System.getProperty("user.dir")+"\\Notes\\流\\zip\\result.zip");
ZipOutputStream zipOut = new ZipOutputStream(new BufferedOutputStream(new FileOutputStream(toFile)));
ZipEntry ze = new ZipEntry(fromFile1.getName());
zipOut.putNextEntry(ze);
int bytes = -1;
while((bytes=in1.read())!=-1){
zipOut.write(bytes);
}
in1.close();
zipOut.closeEntry();
ze = new ZipEntry(fromFile2.getName());
zipOut.putNextEntry(ze);
while((bytes=in2.read())!=-1){
zipOut.write(bytes);
}
in2.close();
zipOut.closeEntry();
zipOut.close();
}catch(Exception e){
e.printStackTrace();
}
}