java.util.zip内容详解(一)
zip主功能是压缩数据,注意并不是数据并不一定是文件,细分可以分为三个小部分,第一个是校验和,第二个是压缩算法的实现,第三部是压缩的具体实现也就是对压缩算法和校验和同意做了封装
先说第一小部分,就是校验和,先看代码
public interface Checksum { public void update(int b); public void update(byte[] b, int off, int len); public long getValue(); public void reset(); }
校验和是校验全部数据的和,所以可以通过update往要校验的数据里添加数据,getValue用于获取校验和,reset相当于重置待校验缓冲区,看简单Demo
public static void main(String[] args) { Checksum cs = new CRC32(); ByteBuffer buffer = ByteBuffer.allocate(10); buffer.asIntBuffer().put(100); cs.update(buffer.array(), 0, 10); System.out.println(cs.getValue()); cs.reset(); cs.update(buffer.array(), 0, 10); System.out.print(cs.getValue()); }
这一部分关系可以由一下图来表示

两个Stream,跟一般Stream的区别在于它里面有一个CheckSum类型的字段,用于记录读取或是写入数据的校验和。Demo如下
public static void main(String[] args) throws IOException { CheckedOutputStream cos = new CheckedOutputStream(new ByteArrayOutputStream(),new CRC32()); cos.write(1); cos.write(2); cos.write(3); cos.write(4); cos.write(5); System.out.println(cos.getChecksum().getValue()); }
浙公网安备 33010602011771号