FileDigestUtil { public byte[] getFileMd5Sum(Path unpackFile) { if (md == null || !unpackFile.toFile().exists()) { LOG.debug("MD is null {}, or file does not exist {}", md, unpackFile); return new byte[0]; } try (InputStream is = Files.newInputStream(unpackFile)) { DigestInputStream dis = new DigestInputStream(is, md); while ((dis.read()) != -1) ; byte[] digest = md.digest(); md.reset(); return digest; } catch (IOException e) { LOG.error("Error calculating MD5 sum", e); return new byte[0]; } } FileDigestUtil(); byte[] getFileMd5Sum(Path unpackFile);  }
@Test public void testFileMd5SumEquals_SameFile() throws Exception { Path path1 = Paths.get(FileDigestUtilTest.class.getResource("file1.txt").toURI()); Path path2 = Paths.get(FileDigestUtilTest.class.getResource("file1.txt").toURI()); byte[] digest1 = fileDigestUtil.getFileMd5Sum(path1); byte[] digest2 = fileDigestUtil.getFileMd5Sum(path2); assertTrue(Arrays.equals(digest1, digest2)); }
@Test public void testFileMd5SumEquals_OtherFile_SameContent() throws Exception { Path path1 = Paths.get(FileDigestUtilTest.class.getResource("file1.txt").toURI()); Path path2 = Paths.get(FileDigestUtilTest.class.getResource("file2.txt").toURI()); byte[] digest1 = fileDigestUtil.getFileMd5Sum(path1); byte[] digest2 = fileDigestUtil.getFileMd5Sum(path2); assertTrue(Arrays.equals(digest1, digest2)); }
@Test public void testFileMd5SumNotEquals() throws Exception { Path path1 = Paths.get(FileDigestUtilTest.class.getResource("file1.txt").toURI()); Path path2 = Paths.get(FileDigestUtilTest.class.getResource("file3.txt").toURI()); byte[] digest1 = fileDigestUtil.getFileMd5Sum(path1); byte[] digest2 = fileDigestUtil.getFileMd5Sum(path2); assertFalse(Arrays.equals(digest1, digest2)); }
@Test public void testFileMd5SumNotEquals_NotExistingFile() throws Exception { Path path1 = Paths.get(FileDigestUtilTest.class.getResource("file1.txt").toURI()); Path path2 = Paths.get("doesnotexist.txt"); byte[] digest1 = fileDigestUtil.getFileMd5Sum(path1); byte[] digest2 = fileDigestUtil.getFileMd5Sum(path2); assertFalse(Arrays.equals(digest1, digest2)); }
@Test public void testFileMd5SumNotEquals_NotExistingFileBoth() throws Exception { Path path1 = Paths.get("doesnotexist.txt"); Path path2 = Paths.get("doesnotexist.txt"); byte[] digest1 = fileDigestUtil.getFileMd5Sum(path1); byte[] digest2 = fileDigestUtil.getFileMd5Sum(path2); assertTrue(Arrays.equals(digest1, digest2)); }