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();

	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值