支持ZIP格式的Java库更加全面。利用该库可以方便地保存多个文件,他甚至有一个独立的类,是的读取ZIP文件更加方便。这个类库使用的是标准ZIP格式,所以能与当前那些可通过因特网下载的压缩工具很好的协作。使用zip保存,需要使用Checksum类来计算和校验文件的校验和的方法。一共有两种Checksum类型:Adler32(它快一些)和CRC32(慢一些,但更准确)。
package java186;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.util.Enumeration;
import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;
import java.util.zip.CheckedOutputStream;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
public class ZipCompress {
public static void main(String[] args) throws Exception{
args = new String[3];
args[0] = "d:/file/data.txt";
args[1] = "d:/file/DirList.java";
args[2] = "test.txt";
FileOutputStream f = new FileOutputStream("d:/file/test.zip");
CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
ZipOutputStream zos = new ZipOutputStream(csum);
BufferedOutputStream out = new BufferedOutputStream(zos);
zos.setComment("A test of Java Zipping");
for(String arg : args){
System.out.println("writing file: "+arg);
BufferedReader in = new BufferedReader(new FileReader(arg));
zos.putNextEntry(new ZipEntry(arg));
int c;
while((c=in.read())!=-1){
out.write(c);
}
in.close();
out.flush();
}
out.close();
System.out.println("CheckSum: "+csum.getChecksum().getValue());
System.out.println("Reading file");
FileInputStream fi = new FileInputStream("d:/file/test.zip");
CheckedInputStream csumi = new CheckedInputStream(fi, new Adler32());
ZipInputStream in2 = new ZipInputStream(csumi);
BufferedInputStream bis = new BufferedInputStream(in2);
ZipEntry ze;
while((ze=in2.getNextEntry())!=null){
System.out.println("Reading file "+ze);
int x;
while((x=bis.read())!=-1){
System.out.write(x);
}
}
if(args.length==1)System.out.println("Checksum: "+csumi.getChecksum().getValue());
bis.close();
ZipFile zf = new ZipFile("d:/file/test.zip");
Enumeration e = zf.entries();
while(e.hasMoreElements()){
ZipEntry ze2 = (ZipEntry) e.nextElement();
System.out.println("File: "+ze2);
}
}
}
为了能够解压缩文件,ZipInputStream提供了一个getNextEntry()方法返回下一个ZipEntry(如果存在的话)。解压缩文件有一个更简便的方法-------利用ZipFile对象读取文件。该对象有个entries()方法用来向ZipEntries返回一个Enumeration(枚举)。