Android 生成文件MD5

2019-10-09  本文已影响0人  惟吾德馨_慧

1.文件生成MD5工具类

/**
     * SD卡文件MD5文件校验
     *
     * @param file
     * @return
     */
    public static String file2MD5(File file) {

        try {
            byte[] hash;
            byte[] buffer = new byte[8192];
            MessageDigest md = MessageDigest.getInstance("MD5");
            FileInputStream fis = new FileInputStream(file);
            int len;
            while ((len = fis.read(buffer)) != -1) {
                md.update(buffer, 0, len);
            }
            hash = md.digest();

            //对生成的16字节数组进行补零操作
            StringBuilder hex = new StringBuilder(hash.length * 2);
            for (byte b : hash) {
                if ((b & 0xFF) < 0x10) {
                    hex.append("0");
                }
                hex.append(Integer.toHexString(b & 0xFF));
            }
            return hex.toString();
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("NoSuchAlgorithmException", e);
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("UnsupportedEncodingException", e);
        } catch (IOException e) {
            e.printStackTrace();
        }

        return "";

    }

2.应用场景:写文件的内容较大,需要通过MD5来校验文件的完整性,每个文件有一个唯一的MD5值,获取MD5值作为文件名的一部分。

在运用过程中,写文件的IO流应该先关闭再来获取文件的MD5值,只有在关闭后,文件才算完整,此时的MD5值才有效。

jsonWriter.close();
String file2MD5 = file2MD5(file);

获取文件的MD5重命名后MD5值不变

MD5校验工具下载
百度网盘链接:https://pan.baidu.com/s/1fHNclsjeyQpC40gFe8xa0w
提取码:719c

每天进步一点点。。。(2019-10-09)

上一篇下一篇

猜你喜欢

热点阅读