java用Zip举办多文件生存
提供了Zip支持的Java 1.1库显得越发全面。操作它可以利便地生存多个文件。甚至有一个独立的类来简化对Zip文件的读操纵。这个库采回收的是尺度Zip名目,所以能与当前因特网上利用的大量压缩、解压东西很好地协作。下面这个例子采纳了与前例沟通的形式,但能按照我们需要节制任意数量的呼吁行参数。除此之外,它展示了如何用Checksum类来计较和校验文件的“校验和”(Checksum)。可选用两种范例的Checksum:Adler32(速度要快一些)和CRC32(慢一些,但更精确)。
//: ZipCompress.java
// Uses Java 1.1 Zip compression to compress
// any number of files whose names are passed
// on the command line.
import java.io.*;
import java.util.*;
import java.util.zip.*;
public class ZipCompress {
public static void main(String[] args) {
try {
FileOutputStream f =
new FileOutputStream("test.zip");
CheckedOutputStream csum =
new CheckedOutputStream(
f, new Adler32());
ZipOutputStream out =
new ZipOutputStream(
new BufferedOutputStream(csum));
out.setComment("A test of Java Zipping");
// Can't read the above comment, though
for(int i = 0; i < args.length; i++) {
System.out.println(
"Writing file " + args[i]);
BufferedReader in =
new BufferedReader(
new FileReader(args[i]));
out.putNextEntry(new ZipEntry(args[i]));
int c;
while((c = in.read()) != -1)
out.write(c);
in.close();
}
out.close();
// Checksum valid only after the file
// has been closed!
System.out.println("Checksum: " +
csum.getChecksum().getValue());
// Now extract the files:
System.out.println("Reading file");
FileInputStream fi =
new FileInputStream("test.zip");
CheckedInputStream csumi =
new CheckedInputStream(
fi, new Adler32());
ZipInputStream in2 =
new ZipInputStream(
new BufferedInputStream(csumi));
ZipEntry ze;
System.out.println("Checksum: " +
csumi.getChecksum().getValue());
while((ze = in2.getNextEntry()) != null) {
System.out.println("Reading file " + ze);
int x;
while((x = in2.read()) != -1)
System.out.write(x);
}
in2.close();
// Alternative way to open and read
// zip files:
ZipFile zf = new ZipFile("test.zip");
Enumeration e = zf.entries();
while(e.hasMoreElements()) {
ZipEntry ze2 = (ZipEntry)e.nextElement();
System.out.println("File: " + ze2);
// ... and extract the data as before
}
} catch(Exception e) {
e.printStackTrace();
}
}
} ///:~
对付要插手压缩档的每一个文件,都必需挪用putNextEntry(),并将其通报给一个ZipEntry工具。ZipEntry工具包括了一个成果全面的接口,操作它可以获取和配置Zip文件内谁人特定的Entry(进口)上可以或许接管的所有数据:名字、压缩后和压缩前的长度、日期、CRC校验和、特别字段的数据、注释、压缩要领以及它是否一个目次进口等等。然而,固然Zip名目提供了配置暗码的要领,但Java的Zip库没有提供这方面的支持。并且尽量CheckedInputStream和CheckedOutputStream同时提供了对Adler32和CRC32校验和的支持,可是ZipEntry只支持CRC的接口。这固然属于下层Zip名目标限制,但却限制了我们利用速度更快的Adler32。
为解压文件,ZipInputStream提供了一个getNextEntry()要领,能在有的前提下返回下一个ZipEntry。作为一个更简捷的要领,可以用ZipFile工具读取文件。该工具有一个entries()要领,可觉得ZipEntry返回一个Enumeration(列举)。
为读取校验和,必需几多拥有对关联的Checksum工具的会见权限。在这里保存了指向CheckedOutputStream和CheckedInputStream工具的一个句柄。可是,也可以只占有指向Checksum工具的一个句柄。
Zip流中一个令人狐疑的要领是setComment()。正如前面展示的那样,我们可在写一个文件时配置注释内容,但却没有步伐取出ZipInputStream内的注释。看起来,好像只能通过ZipEntry逐个进口地提供对注释的完全支持。
虽然,利用GZIP或Zip库时并不只仅限于文件——可以压缩任何对象,包罗要通过网络毗连发送的数据。