Advertisement
Guest User

Untitled

a guest
Feb 13th, 2016
54
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.61 KB | None | 0 0
  1. package ru.ifmo.ctddev.startsev.walk;
  2.  
  3. import java.io.IOException;
  4. import java.io.InputStream;
  5. import java.nio.charset.StandardCharsets;
  6. import java.nio.file.Files;
  7. import java.nio.file.Path;
  8. import java.nio.file.Paths;
  9. import java.nio.file.StandardOpenOption;
  10. import java.security.MessageDigest;
  11. import java.security.NoSuchAlgorithmException;
  12. import java.util.List;
  13.  
  14. /**
  15.  * Created by sandwwraith(@gmail.com)
  16.  * ITMO University, 2016
  17.  **/
  18. public class Utils {
  19.  
  20.     public static String MD5(Path filepath) throws NoSuchAlgorithmException, IOException {
  21.         MessageDigest digest = MessageDigest.getInstance("MD5");
  22.         try (InputStream stream = Files.newInputStream(filepath, StandardOpenOption.READ)) {
  23.             byte[] buffer = new byte[1024];
  24.             int c;
  25.             while ((c = stream.read(buffer)) >= 0) {
  26.                 digest.update(buffer, 0, c);
  27.             }
  28.  
  29.             StringBuilder builder = new StringBuilder();
  30.             for (byte b : digest.digest()) {
  31.                 builder.append(String.format("%02X", b));
  32.             }
  33.             return builder.toString();
  34.         }
  35.  
  36.     }
  37.  
  38.     public static String MD5FormatIgnoreIOError(Path filepath) {
  39.         String s;
  40.         try {
  41.             s = Utils.MD5(filepath);
  42.         } catch (IOException e) {
  43.             s = "00000000000000000000000000000000";
  44.         } catch  (NoSuchAlgorithmException e) {
  45.             System.err.println("MD5 is not supported on this machine");
  46.             System.exit(-1);
  47.             s = "UNREACHABLE CODE";
  48.         }
  49.         s += " " + filepath.toString();
  50.         return s;
  51.     }
  52. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement