您的位置:首页 > 其它

用于提供一个校验和计算的例子,如何使用该文件的CRC - 32校验引擎。

2015-02-27 16:31 507 查看
package util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;

/**
* @ClassName: ChecksumCRC32
* @Description: TODO(用于提供一个校验和计算的例子,如何使用该文件的CRC - 32校验引擎。)
*/
public class ChecksumCRC32 {

    private static void doChecksum(String fileName) {
        try {
            CheckedInputStream cis = null;
            long fileSize = 0;
            try {
                // Computer CRC32 checksum
                cis = new CheckedInputStream(new FileInputStream(fileName), new CRC32());
                fileSize = new File(fileName).length();
            } catch (FileNotFoundException e) {
                System.err.println("File not found.");
                System.exit(1);
            }
            byte[] buf = new byte[128];
            while(cis.read(buf) >= 0) {
            }
            long checksum = cis.getChecksum().getValue();
            System.out.println(checksum + " " + fileSize + " " + fileName);
        } catch (IOException e) {
            e.printStackTrace();
            System.exit(1);
        }
    }

    public static long getByteCrc32(byte[] data){
        CRC32 crc32 = new CRC32();
        crc32.update(data);
        return crc32.getValue();
    }

    /**
     * Sole entry point to the class and application.
     * @param args Array of String arguments.
     * @throws IOException 
     * @throws FileNotFoundException 
     */
    public static void main(String[] args) throws FileNotFoundException, IOException {
         doChecksum("c://45.png");
         CRC32 crc32 = new CRC32();
        byte[] data = new byte[new FileInputStream("c://45.png").available()];
        new FileInputStream("c://45.png").read(data); 
        crc32.update(data);
        System.out.println(crc32.getValue());
    }
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐