Java MD5 String md5FromFile(File file)

Here you can find the source of md5FromFile(File file)

Description

md From File

License

LGPL

Declaration

static public String md5FromFile(File file) throws IOException 

Method Source Code


//package com.java2s;
//License from project: LGPL 

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    static public String md5FromFile(File file) throws IOException {
        if (!file.exists()) {
            return "";
        }//ww  w.ja  v a2s  .c  o  m

        MessageDigest md = null;
        try {
            md = MessageDigest.getInstance("MD5");
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        byte[] buffer = new byte[8192];

        try (InputStream is = new FileInputStream(file)) {
            DigestInputStream dis = new DigestInputStream(is, md);

            while (dis.read(buffer) != -1)
                ;
        }
        byte[] digest = md.digest();
        StringBuffer sb = new StringBuffer("");
        for (int i = 0; i < digest.length; i++) {
            sb.append(Integer.toString((digest[i] & 0xff) + 0x100, 16).substring(1));
        }

        return sb.toString();
    }

    static public String read(InputStream stream) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(stream));
        StringBuilder builder = new StringBuilder();

        String line;

        while ((line = reader.readLine()) != null) {
            builder.append(line);
            builder.append("\n");
        }

        return builder.toString();
    }
}

Related

  1. md5Encrypt(String str)
  2. md5Encrypt(String str)
  3. md5Encryption(String str)
  4. md5File(File f)
  5. md5file(File file)
  6. md5fromFile(String path)
  7. md5Hex(String data)
  8. md5Hex(String data)
  9. md5Hex(String message)