概述
Java I/O类库中的类支持读写压缩格式的数据流。它们属于InputStream和OutputStream继承层次结构的一部分。
这些类包括:
CheckedInputStream :GetCheckSum为任何InputStream产生效验和。
CheckedOutputStream : GetCheckSum为任何OutputStream产生效验和。
DeflaterOutputStream : 压缩类的基类
ZipOutputStream ::一个DeflaterOutputStream,将数据压缩成zip 文件格式
GZIPOutputStream : 一个DeflaterOutputStream,将数据压缩成gzip文件格式
InflaterInputStream: 解压缩类的基类
ZipInputStream: 一个InflaterInputStream,解压缩Zip文件格式的数据
GZIPInputStream : 一个InflaterInputStream,解压缩gzip文件格式的数据
用GZIP进行简单压缩
GZIP接口非常简单,如果我们只想对单个数据流进行压缩,它比较合适。
import java.util.zip.*;
import java.io.*;
public class GZIPcompress {
public static void main(String[] args)
throws IOException {
if(args.length == 0) {
System.out.println(
"Usage: \nGZIPcompress file\n" +
"\tUses GZIP compression to compress " +
"the file to test.gz");
System.exit(1);
}
BufferedReader in = new BufferedReader(
new FileReader(args[0]));
//用GZIPOutputStream 压缩文件
BufferedOutputStream out = new BufferedOutputStream(
new GZIPOutputStream(
new FileOutputStream("test.gz")));
System.out.println("Writing file");
int c;
while((c = in.read()) != -1)
out.write(c);
in.close();
out.close();
System.out.println("Reading file");
//读压缩文件
BufferedReader in2 = new BufferedReader(
new InputStreamReader(new GZIPInputStream(
new FileInputStream("test.gz"))));
String s;
while((s = in2.readLine()) != null)
System.out.println(s);
}
}
用Zip进行多文件保存
支持Zip格式的Java库更加全面。可以方便地保存多个文件。
import java.util.zip.*;
import java.io.*;
import java.util.*;
public class ZipCompress {
public static void main(String[] args) throws IOException {
FileOutputStream f = new FileOutputStream("test.zip");
//设置流的效验方式,共有2种:Adler32(快一些)和CRC32(慢一些,但更准确)
CheckedOutputStream csum = new CheckedOutputStream(f, new Adler32());
ZipOutputStream zos = new ZipOutputStream(csum);
BufferedOutputStream out = new BufferedOutputStream(zos);
//设置comment,但是没有get的方法.
zos.setComment("A test of Java Zipping");
//把所有文件都添加到zip流中,只能通过putNextEntry方法添加.
for (String arg : args) {
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();
// 读取Checksum值,只有在zip流关闭时才准确
System.out.println("CheckSum:" + csum.getChecksum().getValue());
//解压缩文件:
System.out.println("Reading file");
FileInputStream fi = new FileInputStream("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) {
int x;
while ((x = bis.read()) != -1)
System.out.write(x);
}
System.out.println("CheckSum:" + csumi.getChecksum().getValue());
bis.close();
// 更方便的读写zip文件的方法:
ZipFile zf = new ZipFile("test.zip");
Enumeration e = zf.entries();
while (e.hasMoreElements()) {
ZipEntry ze2 = (ZipEntry) e.nextElement();
}
}
}