Java 對文件進行 CRC32 校驗

833p 9年前發布 | 3K 次閱讀 Java

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

/**



*/

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);
    }


}


/**
 * Sole entry point to the class and application.
 * @param args Array of String arguments.
 */
public static void main(String[] args) {

    if (args.length != 1) {
        System.err.println("Usage: java ChecksumCRC32 filename");
    } else {
        doChecksum(args[0]);
    }

}

}</pre>

 本文由用戶 833p 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!