FileUtil { public static final String getDigest(File _file, DigestAlgorithm _alg) { try { if (!_file.canRead()) throw new IOException("Cannot read file"); final MessageDigest md = MessageDigest.getInstance(_alg.toString()); try (final InputStream is = new FileInputStream(_file); final DigestInputStream dis = new DigestInputStream(is, md); ) { byte[] bytes = new byte[1024]; while (dis.read(bytes, 0, 1024) != -1) { ; } byte[] digest = md.digest(); return DigestUtil.bytesToHex(digest); } } catch (NoSuchAlgorithmException e) { FileUtil.log.error("Error while instantiating [" + _alg + "] digest: " + e.getMessage()); } catch (IOException e) { FileUtil.log.error("IO Error while computing [" + _alg + "] digest: " + e.getMessage()); } catch (ArrayIndexOutOfBoundsException be) { FileUtil.log.error("Error while computing [" + _alg + "] digest: " + be.getMessage()); } return null; }  static String getFileExtension(File _file); static boolean hasFileExtension(Path _p, String[] _extensions); static String toString(Set<Path> _paths, String _sep); static Path createTmpDir(String _prefix); static boolean isAccessibleFile(String _arg); static boolean isAccessibleFile(Path _arg); static final boolean isAccessibleDirectory(Path _dir); static final boolean isAccessibleDirectory(File _dir); static final boolean isAccessibleDirectory(String _dir); static final void createDirectory(Path _p); static String getFileName(String _file_path); static String getFileName(String _file_path, boolean _keep_ext); static String getCharsetName(); static Charset getCharset(); static Path copyFile(Path _source_file, Path _target_dir); static String readFile(String _p); static String readFile(Path _p); static String readInputStream(InputStream _is, Charset _cs); static byte[] readInputStream(InputStream _is); static final void writeToFile(File _f, String _content); static final Path writeToTmpFile(String _filename, String _suffix, String _content); static final void writeToFile(File _f, byte[] _content); static Set<Path> getPaths(String[] _paths); static Path getPath(String _path, boolean _create); static Path getPath(String _path); static final String getSHA1(File _file); static final String getDigest(File _file, DigestAlgorithm _alg); static String getJarFilePath(Class<?> _clazz); static String getJarFilePath(String _url); static Set<String> getJarFilePathsForResources(ClassLoader _cl, String[] _resources); static Set<String> getJarFilePaths(URLClassLoader _cl); static Boolean isZipped(File _f);  }
@Test public void testGetDigest() { final File f = new File("./src/test/resources/foo.txt"); final String sha1 = FileUtil.getSHA1(f).toLowerCase(); final String expected_sha1 = "c7567e8b39e2428e38bf9c9226ac68de4c67dc39"; assertEquals(expected_sha1, sha1); final String md5 = FileUtil.getDigest(f, DigestAlgorithm.MD5).toLowerCase(); final String expected_md5 = "ab07acbb1e496801937adfa772424bf7"; assertEquals(expected_md5, md5); }