Android中获取文件的md5,解决首位0被省略问题,解决超大文件问题

Android中获取文件的md5,如果首位是0会被省略:

解决方法:https://blog.csdn.net/dodod2012/article/details/107631510

但是采用上面的方法,如果文件超过2G,会超过 FileChannel 的 map 方法中 size 参数大小限制,源码中发现该参数值大于 Integer.MAX_VALUE 时会直接抛出 IllegalArgumentException(“Size exceeds Integer.MAX_VALUE”) 异常,所以对于特别大的文件其依然不适合。

解决方法结合这篇文章:https://blog.csdn.net/ff00yo/article/details/88778643

 

下面是Android中获取文件md5值得最终写法。

public class MD5Util {


	private static MappedByteBuffer[] mappedByteBuffers;
	private static int bufferCount;

	/**
	 * 获取单个文件的MD5值!

	 * @param file
	 * @return
	 * 解决首位0被省略问题
	 * 解决超大文件问题
	 */

	public static String getFileMD5(File file) {

		StringBuffer stringbuffer = null;
		try {
			char[] hexDigits = { '0', '1', '2','3', '4','5', '6','7','8', '9', 'a','b' ,'c', 'd','e', 'f' };
			FileInputStream in = new FileInputStream(file);
			FileChannel ch = in.getChannel();

			long fileSize = ch.size();
			bufferCount = (int) Math.ceil((double) fileSize / (double) Integer.MAX_VALUE);
			mappedByteBuffers = new MappedByteBuffer[bufferCount];

			long preLength = 0;
			long regionSize = Integer.MAX_VALUE;
			for (int i = 0; i < bufferCount; i++) {
				if (fileSize - preLength < Integer.MAX_VALUE) {
					regionSize = fileSize - preLength;
				}
				mappedByteBuffers[i] = ch.map(FileChannel.MapMode.READ_ONLY, preLength, regionSize);
				preLength += regionSize;
			}

			MessageDigest messagedigest = MessageDigest.getInstance("MD5");

			for(int i = 0; i < bufferCount; i ++){
				messagedigest.update(mappedByteBuffers[i]);
			}
			byte[] bytes = messagedigest.digest();
			int n = bytes.length;
			stringbuffer = new StringBuffer(2 * n);
			for (int l = 0; l < n; l++) {
				byte bt = bytes[l];
				char c0 = hexDigits[(bt & 0xf0) >> 4];
				char c1 = hexDigits[bt & 0xf];
				stringbuffer.append(c0);
				stringbuffer.append(c1);
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return stringbuffer.toString();

	}
}

 

©️2020 CSDN 皮肤主题: 书香水墨 设计师:CSDN官方博客 返回首页