Java Checksum Calculate getChecksum(final File file)

Here you can find the source of getChecksum(final File file)

Description

Returns the Adler32 checksum of the contents of a given File .

License

Apache License

Parameter

Parameter Description
file the File to calculate the checksum from

Return

the resulting checksum as long value

Declaration

public static long getChecksum(final File file) 

Method Source Code


//package com.java2s;
//License from project: Apache License 

import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;

import java.util.zip.Adler32;
import java.util.zip.CheckedInputStream;

public class Main {
    /**//from   w w w .  jav a  2 s. c  o m
     * Returns the {@link Adler32} checksum of the contents of a given
     * {@link File}.
     * 
     * @param file
     *           the {@link File} to calculate the checksum from
     * @return the resulting checksum as {@code long} value
     */
    public static long getChecksum(final File file) {
        if (file.isDirectory()) {
            return 0L;
        }

        CheckedInputStream cis = null;
        try {
            cis = new CheckedInputStream(new FileInputStream(file), new Adler32());

            final byte[] tempBuf = new byte[8192];

            final Thread currentThread = Thread.currentThread();

            while (cis.read(tempBuf) >= 0) {
                if (currentThread.isInterrupted()) {
                    return 0L;
                }
            }

            return cis.getChecksum().getValue();
        } catch (final IOException e) {
            return 0L;
        } finally {
            if (cis != null) {
                try {
                    cis.close();
                } catch (final IOException e) {
                }
            }
        }
    }
}

Related

  1. generateChecksum(InputStream is)
  2. generateChecksum(String path, String flavor)
  3. generateChecksum(String pType, String pInFile)
  4. generateCheckSum(String string)
  5. getChecksum(byte[] buffer, int offset, int length)
  6. getCheckSum(String filePath)
  7. getChecksumAlder32(File file)
  8. getCheckSums(String archiveFile)