Android获取文件MD5
通过 java.security 包下的MessageDigest
工具,可以简单快捷的直接计算出文件的MD5值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| fun getFileMd5(path: String?): String? { if (path == null || path.isEmpty()) { return "" } try { val messagedigest = MessageDigest.getInstance("MD5") val buf = ByteArray(4096) var n: Int val fis = FileInputStream(path) while (fis.read(buf, 0, 4096).also { n = it } > 0) { messagedigest.update(buf, 0, n) } fis.close() return HexUtils.toHexString(messagedigest.digest()) } catch (e: Exception) { e.printStackTrace() } return "" }
|
1 2 3 4 5 6 7 8 9 10 11 12 13
| private static char[] hexDigits = {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};
static String toHexString(byte[] bytes) { StringBuilder sb = new StringBuilder(2 * bytes.length); for (int l = 0; l < bytes.length; l++) { char c0 = hexDigits[(bytes[l] & 0xf0) >> 4]; char c1 = hexDigits[bytes[l] & 0xf]; sb.append(c0); sb.append(c1); } return sb.toString(); }
|