计算文件MD5值的多种方法

计算文件MD5值的多种方法

  • 方法一:CMD计算本地文件
  • 方法二:Java计算上传文件
  • 方法三:Java计算本地文件
      • demo1
      • demo2

方法一:CMD计算本地文件

进入cmd,输入命令

// F:\a.txt是文件路径
certutil -hashfile F:\a.txt MD5

如下所示:
计算文件MD5值的多种方法_第1张图片

方法二:Java计算上传文件

import org.springframework.web.multipart.MultipartFile;
import java.security.MessageDigest;
import java.io.File;

public String geMD5(MultipartFile file) throws Exception {
    		MessageDigest mMessageDigest  = MessageDigest.getInstance("MD5");
    		InputStream fis = file.getInputStream();
    		byte[] buffer = new byte[1024];
    		int length = -1;
    		while ((length = fis.read(buffer, 0, 1024)) > 0) {
    			mMessageDigest.update(buffer, 0, length);
    		}
    		fis.close();
    		return new BigInteger(1, mMessageDigest.digest()).toString(16);
    }

方法三:Java计算本地文件

demo1

import org.apache.commons.codec.binary.Hex;
import java.security.MessageDigest;
import java.io.File;
import java.io.FileInputStream;

private String getMD5(String filePath) throws Exception {
		File file = new File(filePath);
		FileInputStream fis= new FileInputStream(file);
		MessageDigest MD5 = MessageDigest.getInstance("MD5");
		byte[] buffer = new byte[1024];
		int length;
		while ((length = fis.read(buffer)) != -1) {
			MD5.update(buffer, 0, length);
		}
		fis.close();
		return new String(Hex.encodeHex(MD5.digest()));
	}

demo2

import org.apache.commons.codec.binary.Hex;
import java.security.MessageDigest;
import java.io.File;
import java.io.FileInputStream;

private String getMD5(String filePath) throws Exception {
		File file = new File(filePath);
		MessageDigest MD5 = MessageDigest.getInstance("MD5");
		FileInputStream fis = new FileInputStream(file);
		byte[] buffer = new byte[1024];
		int length = -1;
		while ((length = fis.read(buffer, 0, 1024)) > 0) {
			MD5.update(buffer, 0, length);
		}
		fis.close();
		return new BigInteger(1, MD5.digest()).toString(16);
	}

你可能感兴趣的:(Java)