6.6.3 实现

在Java 6中,CRC-32算法是由CRC32类来实现的。


//可用于计算数据流的CRC-32的类。

public class CRC32

extends Object

implements Checksum


CRC32类使用起来极为简单,通过其无参构造方法完成实例化对象后,需要先执行以下update()方法:


//使用指定的字节数组更新校验和。

public void update(byte[]b)

//使用指定的字节数组更新CRC-32。

public void update(byte[]b, int off, int len)

//使用指定字节更新CRC-32。

public void update(int b)


update()方法可多次执行,此后执行getValue()方法:


//返回CRC-32值。

public long getValue()


执行完上述方法后,我们可以获得一个长整型的冗余校验码,可通过Long类的toHexString()方法将其转换为十六进制字符串形式。

如需重置,需执行如下方法:


//将CRC-32重置为初始值。

public void reset()


除此之外,还有CheckedInputStream和CheckedOutputStream两个类,可用于输入输出流的冗余校验处理。对于Adler-32算法,请使用Adler32类。Adler32类同样实现了Checksum接口,其方法与CRC32相同。

CRC32算法实现较为简单,如代码清单6-21所示。

代码清单6-21 CRC32算法实现


import java.util.zip.CRC32;

import org.junit.Test;

/**

*测试CRC-32

*@author梁栋

*@version 1.0

*@since 1.0

*/

public class CRCTest{

/**

*测试CRC-32

*@throws Exception

*/

@Test

public void testCRC32()throws Exception{

String str="测试CRC-32";

CRC32 crc32=new CRC32();

crc32.update(str.getBytes());

String hex=Long.toHexString(crc32.getValue());

System.err.println("原文:\t"+str);

System.err.println("CRC-32:\t"+hex);

}

}


执行上述代码后,在控制台中得到如下内容:


原文:测试CRC-32

CRC-32:eda03da1


原文经CRC-32算法处理后得到了一个8位十六进制字符串。

对上述代码稍作调整,就可用于文件校验。