java 获取文件MD5值

本文介绍了一种在Java中实现文件MD5校验的方法,包括获取文件的MD5值及通过比较两个文件的MD5值来判断它们是否完全相同的技术细节。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java 中,如何获取文件的MD5值呢?如何比较两个文件是否完全相同呢?

/**
	 * Get MD5 of one file:hex string,test OK!
	 * 
	 * @param file
	 * @return
	 */
	public static String getFileMD5(File file) {
		if (!file.exists() || !file.isFile()) {
			return null;
		}
		MessageDigest digest = null;
		FileInputStream in = null;
		byte buffer[] = new byte[1024];
		int len;
		try {
			digest = MessageDigest.getInstance("MD5");
			in = new FileInputStream(file);
			while ((len = in.read(buffer, 0, 1024)) != NEGATIVE_ONE) {
				digest.update(buffer, 0, len);
			}
			in.close();
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
		BigInteger bigInt = new BigInteger(1, digest.digest());
		return bigInt.toString(16);
	}

	/***
	 * Get MD5 of one file!test ok!
	 * 
	 * @param filepath
	 * @return
	 */
	public static String getFileMD5(String filepath) {
		File file = new File(filepath);
		return getFileMD5(file);
	}

	/**
	 * MD5 encrypt,test ok
	 * 
	 * @param data
	 * @return byte[]
	 * @throws Exception
	 */
	public static byte[] encryptMD5(byte[] data) throws Exception {

		MessageDigest md5 = MessageDigest.getInstance(SystemUtil.KEY_MD5);
		md5.update(data);
		return md5.digest();
	}

	public static byte[] encryptMD5(String data) throws Exception {
		return encryptMD5(data.getBytes(SystemUtil.CHARSET_ISO88591));
	}
	/***
	 * compare two file by Md5
	 * 
	 * @param file1
	 * @param file2
	 * @return
	 */
	public static boolean isSameMd5(File file1,File file2){
		String md5_1=SystemUtil.getFileMD5(file1);
		String md5_2=SystemUtil.getFileMD5(file2);
		return md5_1.equals(md5_2);
	}
	/***
	 * compare two file by Md5
	 * 
	 * @param filepath1
	 * @param filepath2
	 * @return
	 */
	public static boolean isSameMd5(String filepath1,String filepath2){
		File file1=new File(filepath1);
		File file2=new File(filepath2);
		return isSameMd5(file1, file2);
	}

 测试(使用junit):

@Test
	public void test_getFileMD5() throws Exception{
		String filepath="D:\\download\\3_尚学堂_UML概览.avi";
//		File file=new File(filepath);
		String md5_1=SystemUtil.getFileMD5(filepath);
		System.out.println(md5_1);
		
		byte[]bytes=FileUtils.readBytes4file(filepath);
		byte[]md5=SystemUtil.encryptMD5(bytes);
		String md5_2=SystemUtil.toHexString(md5);
		System.out.println(md5_2);
		Assert.assertEquals(md5_1, md5_2);
	}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值