Skip to content

Instantly share code, notes, and snippets.

@xtman
Created January 29, 2022 09:11
Show Gist options
  • Save xtman/e8ea120e996d2af9623b108b59da2318 to your computer and use it in GitHub Desktop.
Save xtman/e8ea120e996d2af9623b108b59da2318 to your computer and use it in GitHub Desktop.
Java utility to generate CRC32 checksums
package unimelb.utils;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.nio.file.Path;
import java.util.zip.CRC32;
import java.util.zip.CheckedInputStream;
public class ChecksumUtils {
public static long getCRC32Value(Path f) throws Throwable {
return getCRC32Value(f.toFile());
}
public static long getCRC32Value(File f) throws Throwable {
InputStream in = new BufferedInputStream(new FileInputStream(f));
try {
return getCRC32Value(in);
} finally {
in.close();
}
};
public static long getCRC32Value(InputStream in) throws Throwable {
CheckedInputStream cin = new CheckedInputStream(
(in instanceof BufferedInputStream) ? in : new BufferedInputStream(in), new CRC32());
byte[] buffer = new byte[1024];
try {
while (cin.read(buffer) != -1) {
// Read file in completely
}
} finally {
cin.close();
in.close();
}
return cin.getChecksum().getValue();
}
public static String getCRC32(Path f) throws Throwable {
return getCRC32(f.toFile());
}
public static String getCRC32(Path f) throws Throwable {
return getCRC32(f.toFile());
}
public static String getCRC32(File f) throws Throwable {
InputStream in = new BufferedInputStream(new FileInputStream(f));
try {
return getCRC32(in);
} finally {
in.close();
}
}
public static String getCRC32(InputStream in) throws Throwable {
CheckedInputStream cin = new CheckedInputStream(
(in instanceof BufferedInputStream) ? in : new BufferedInputStream(in), new CRC32());
byte[] buffer = new byte[1024];
try {
while (cin.read(buffer) != -1) {
// Read file in completely
}
} finally {
cin.close();
in.close();
}
long value = cin.getChecksum().getValue();
return Long.toHexString(value);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment