JAVA实现CRC32校验

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/CNZYYH/article/details/82499272

CRC校验实用程序库 在数据存储和数据通讯领域,为了保证数据的正确,就不得不采用检错的手段。在诸多检错手段中,CRC是最著名的一种。CRC的全称是循环冗余校验。

其特点是:检错能力极强,开销小,易于用编码器及检测电路实现。从其检错能力来看,它所不能发现的错误的几率仅为0.0047%以下。从性能上和开销上考虑,均远远优于奇偶校验及算术和校验等方式。因而,在数据存储和数据通讯领域,CRC无处不在:著名的通讯协议X.25的FCS(帧检错序列)采用的是CRC-CCITT,ARJ、LHA等压缩工具软件采用的是CRC32,磁盘驱动器的读写采用了CRC16,通用的图像存储格式GIF、TIFF等也都用CRC作为检错手段。

Java中已经有实现好的校验函数,简单使用方法。

import java.util.zip.CRC32;
CRC32 crc32 = new CRC32();
crc32.update("abcdfg".getBytes());
System.out.println(crc32.getValue())

对于一个大文件,可以采用流的方式读取大文件:

    public static String getCRC32(File file) {
        CRC32 crc32 = new CRC32();  
        //MessageDigest.get
        FileInputStream fileInputStream = null;
        try {
        fileInputStream = new FileInputStream(file);
            byte[] buffer = new byte[8192];
            int length;
            while ((length = fileInputStream.read(buffer)) != -1) {
                crc32.update(buffer,0, length);
            }
            return crc32.getValue()+"";
        } catch (FileNotFoundException e) {
        e.printStackTrace();
            return null;
        } catch (IOException e) {
        e.printStackTrace();
            return null;
        } finally {
            try {
                if (fileInputStream != null)
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
 

猜你喜欢

转载自blog.csdn.net/CNZYYH/article/details/82499272
今日推荐