get MD5 File - Android java.security

Android examples for java.security:MD5

Description

get MD5 File

Demo Code


//package com.java2s;
import android.text.TextUtils;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {

    public static String getMD5File(String filePath) {
        if (!TextUtils.isEmpty(filePath)) {
            FileInputStream in = null;
            try {
                MessageDigest md = MessageDigest.getInstance("MD5");
                in = new FileInputStream(filePath);
                int len;
                byte[] buffer = new byte[1024];
                while ((len = in.read(buffer)) != -1) {
                    md.update(buffer, 0, len);
                }//from www. j  a  v  a 2s  .  c  o  m
                return bytes2Hex(md.digest());
            } catch (NoSuchAlgorithmException | IOException e) {
                e.printStackTrace();
            } finally {
                if (in != null) {
                    try {
                        in.close();
                    } catch (IOException ignored) {
                    }
                }
            }
        }
        return "";
    }

    public static String bytes2Hex(byte[] src) {
        char[] res = new char[src.length * 2];
        final char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7',
                '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
        for (int i = 0, j = 0; i < src.length; i++) {
            res[j++] = hexDigits[src[i] >>> 4 & 0x0f];
            res[j++] = hexDigits[src[i] & 0x0f];
        }
        return new String(res);
    }
}

Related Tutorials