get MD5 for File - Android File Input Output

Android examples for File Input Output:File Hash

Description

get MD5 for File

Demo Code


//package com.java2s;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.nio.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;

import android.util.Log;

public class Main {
    private static String sTag = "MD5Util";
    private static MessageDigest mMessageDigest;

    public static String getMD5(File file) {
        if (mMessageDigest != null) {
            FileInputStream fis = null;
            MappedByteBuffer byteBuffer = null;
            try {
                fis = new FileInputStream(file);
                FileChannel channel = fis.getChannel();
                byteBuffer = channel.map(FileChannel.MapMode.READ_ONLY, 0,
                        file.length());//from  w w w.j av  a2s  .co m
                mMessageDigest.update(byteBuffer);
            } catch (FileNotFoundException e) {
                Log.e(sTag, "getFileMD5.Exception : " + e.getMessage());
            } catch (IOException e) {
                Log.e(sTag, "getFileMD5.Exception : " + e.getMessage());
            } finally {
                if (fis != null) {
                    try {
                        fis.close();
                    } catch (IOException e) {
                        Log.e(sTag,
                                "getFileMD5.Exception : " + e.getMessage());
                    }
                }
                if (byteBuffer != null) {
                    byteBuffer.clear();
                }
            }
            return bytesToHexString(mMessageDigest.digest());
        }
        return null;
    }

    public static String getMD5(String str) {
        if (str != null) {
            return getMD5(str.getBytes());
        }
        return null;
    }

    public static String getMD5(byte[] bytes) {
        if (mMessageDigest != null && bytes != null) {
            mMessageDigest.update(bytes);
            return bytesToHexString(mMessageDigest.digest());
        }
        return null;
    }

    private static String bytesToHexString(byte[] bytes) {
        if (bytes != null) {
            StringBuffer stringBuffer = new StringBuffer();
            for (int i = 0; i < bytes.length; i++) {
                int v = bytes[i] & 0xFF;
                String hv = Integer.toHexString(v);
                if (hv.length() < 2) {
                    stringBuffer.append(0);
                }
                stringBuffer.append(hv);
            }
            return stringBuffer.toString();
        }
        return null;
    }
}

Related Tutorials