Computes the checksum of a file using the CRC32 checksum routine - Android java.util.zip

Android examples for java.util.zip:CheckedInputStream

Description

Computes the checksum of a file using the CRC32 checksum routine

Demo Code

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;

public class Main{

    /**/*from   ww  w .  j ava  2  s  .com*/
     * Computes the checksum of a file using the CRC32 checksum routine.
     * The value of the checksum is returned.
     *
     * @param file  the file to checksum, must not be null
     * @return the checksum value or an exception is thrown.
     */
    public static long checksumCrc32(File file)
            throws FileNotFoundException, IOException {
        CRC32 checkSummer = new CRC32();
        CheckedInputStream cis = null;

        try {
            cis = new CheckedInputStream(new FileInputStream(file),
                    checkSummer);
            byte[] buf = new byte[128];
            while (cis.read(buf) >= 0) {
                // Just read for checksum to get calculated.
            }
            return checkSummer.getValue();
        } finally {
            if (cis != null) {
                try {
                    cis.close();
                } catch (IOException e) {
                }
            }
        }
    }

}

Related Tutorials