在manifest中添加权限

1 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

注意:

在调用toString方法的时候,如果这个数字是0开头的,会自动去掉这些0。只有当文件的md5值是0开头的时候会出问题。

1 BigInteger bigInt = new BigInteger(1, digest.digest());
2 String value = bigInt.toString(16);

所以有两种方法:

方法一:

1 public static String getMd5ByFile(File file) {
 2         if (!file.exists())
 3             return "";
 4 
 5         String value = null;
 6         try {
 7             FileInputStream in = new FileInputStream(file);
 8 
 9             try {
10                 MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
11 
12                 MessageDigest md5 = MessageDigest.getInstance("MD5");
13                 md5.update(byteBuffer);
14 
15                 BigInteger bi = new BigInteger(1, md5.digest());
16 
17                 value = bi.toString(16);
18 
19                 // 防止文件的md5值以0开头
20                 if (value.length() == 31) {
21                     value = "0" + value;
22                 }
23 
24             } catch (Exception e) {
25                 // throw this exception
26             } finally {
27                 if (null != in) {
28                     in.close();
29                 }
30             }
31         } catch (FileNotFoundException e) {
32              // throw this exception
33         }
34 
35         return value;
36     }

方法二:

1 public static String getFileMD5(File file) {
 2     if (!file.isFile()) {
 3         return null;
 4     }
 5     MessageDigest digest = null;
 6     FileInputStream in = null;
 7     byte buffer[] = new byte[1024];
 8     int len;
 9     try {
10         digest = MessageDigest.getInstance("MD5");
11         in = new FileInputStream(file);
12         while ((len = in.read(buffer, 0, 1024)) != -1) {
13             digest.update(buffer, 0, len);
14         }
15         in.close();
16     } catch (Exception e) {
17         e.printStackTrace();
18         return null;
19     }
20     return bytesToHexString(digest.digest());
21 }

转换方法:

1 public static String bytesToHexString(byte[] src) {
 2     StringBuilder stringBuilder = new StringBuilder("");
 3     if (src == null || src.length <= 0) {
 4         return null;
 5     }
 6     for (int i = 0; i < src.length; i++) {
 7         // java中byte转换为int时与0xFF进行与运算(&)
 8         int v = src[i] & 0xFF;
 9         String hv = Integer.toHexString(v);
10         if (hv.length() < 2) {
11             stringBuilder.append(0);
12         }
13         stringBuilder.append(hv);
14     }
15     return stringBuilder.toString();
16 }

java中byte转换int时与0xff进行与运算:

原因:

1.byte的大小为8bits而int的大小为32bits
2.java的二进制采用的是补码形式

作者:晕菜一员