Saturday, 29 June 2019

Java: Get content hash of the file


FileUtil.java
import java.io.File;
import java.io.FileInputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Optional;

public class FileUtil {
 public static final String MD5 = "md5";

 public static Optional<String> getContentHash(String filePath) {
  if (filePath == null) {
   System.out.println("getContentHash: filePath shouldn't be null");
   return Optional.empty();
  }
  return getContentHash(new File(filePath));
 }

 public static Optional<String> getContentHash(File file) {
  return getContentHash(file, MD5);
 }

 public static Optional<String> getContentHash(File file, String algorithmToUse) {
  if (algorithmToUse == null) {
   System.out.println("getContentHash: algorithmToUse shouldn't be null");
   return Optional.empty();
  }

  if (file == null) {
   System.out.println("getContentHash: file shouldn't be null");
   return Optional.empty();
  }

  if (!file.exists()) {
   System.out.println("getContentHash: file is not exists : " + file);
   return Optional.empty();
  }

  try (FileInputStream inputStream = new FileInputStream(file)) {
   MessageDigest messageDigest = MessageDigest.getInstance(algorithmToUse);
   byte[] bytesBuffer = new byte[1024];
   int bytesRead = -1;

   while ((bytesRead = inputStream.read(bytesBuffer)) != -1) {
    messageDigest.update(bytesBuffer, 0, bytesRead);
   }

   byte[] digest = messageDigest.digest();
   String contentHash = getHexaString(digest);
   return Optional.of(contentHash);

  } catch (NoSuchAlgorithmException e) {
   System.out.println("getContentHash: Invalid algorithm to calculate hash " + algorithmToUse);
   System.out.println(e.getMessage());
   return Optional.empty();
  } catch (Exception e) {
   System.out.println(e.getMessage());
   return Optional.empty();
  }

 }

 private static String getHexaString(byte[] data) {
  String result = new BigInteger(1, data).toString(16);
  return result;
 }
}


FileUtilTest.java
import java.io.FileNotFoundException;
import java.util.Optional;

public class FileUtilTest {

 public static void main(String args[]) throws FileNotFoundException {
  String inputFilePath = "C:\\Users\\input.txt";

  Optional<String> contentHashOpt = FileUtil.getContentHash(inputFilePath);

  if (contentHashOpt.isPresent()) {
   System.out.println("Content Hash : " + contentHashOpt.get());
   return;
  }

  System.out.println("Unable to calculate content hash");

 }
}

Output
Content Hash : b10a8db164e0754105b7a99be72e3fe5



No comments:

Post a Comment