java使用计算md5校验码方式比较两个文件是否相同
时间:2023-05-10 23:43:16
public class MD5Check {
/**
* 默认的密码字符串组合,用来将字节转换成 16 进制表示的字符,apache校验下载的文件的正确性用的就是默认的这个组合
*/
protected char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
protected MessageDigest messagedigest = null;
{
try {
messagedigest = MessageDigest.getInstance("MD5");
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
}
public String getFileMD5String(File file) throws IOException {
InputStream fis;
fis = new FileInputStream(file);
byte[] buffer = new byte[1024];
int numRead = 0;
while ((numRead = fis.read(buffer)) > 0) {
messagedigest.update(buffer, 0, numRead);
}
fis.close();
return bufferToHex(messagedigest.digest());
}
public String getFileMD5String(InputStream in) throws IOException {
byte[] buffer = new byte[1024];
int numRead = 0;
while ((numRead = in.read(buffer)) > 0) {
messagedigest.update(buffer, 0, numRead);
}
in.close();
return bufferToHex(messagedigest.digest());
}
private String bufferToHex(byte bytes[]) {
return bufferToHex(bytes, 0, bytes.length);
}
private String bufferToHex(byte bytes[], int m, int n) {
StringBuffer stringbuffer = new StringBuffer(2 * n);
int k = m + n;
for (int l = m; l < k; l++) {
appendHexPair(bytes[l], stringbuffer);
}
return stringbuffer.toString();
}
private void appendHexPair(byte bt, StringBuffer stringbuffer) {
char c0 = hexDigits[(bt & 0xf0) >> 4];// 取字节中高 4 位的数字转换
// 为逻辑右移,将符号位一起右移,此处未发现两种符号有何不同
char c1 = hexDigits[bt & 0xf];// 取字节中低 4 位的数字转换
stringbuffer.append(c0);
stringbuffer.append(c1);
}
}
![](/images/zang.png)
![](/images/jiucuo.png)
猜你喜欢
Android WebView实现网页滚动截图
![](https://img.aspxhome.com/file/2023/8/88098_0s.jpg)
用c#获得当前用户的Application Data文件夹位置
基于mvc5+ef6+Bootstrap框架实现身份验证和权限管理
Java 数据结构中二叉树前中后序遍历非递归的具体实现详解
![](https://img.aspxhome.com/file/2023/7/75757_0s.png)
C#在Windows窗体控件实现内容拖放(DragDrop)功能
![](https://img.aspxhome.com/file/2023/4/98254_0s.jpg)
Android Studio提示inotify大小不足的解决办法
springboot项目打成war包部署到tomcat遇到的一些问题
RocketMq深入分析讲解两种削峰方式
SpringBoot整合之SpringBoot整合MongoDB的详细步骤
![](https://img.aspxhome.com/file/2023/6/59076_0s.png)
深入了解Java核心类库--BigDecimal和System类
Java中值类型和引用类型详解
![](https://img.aspxhome.com/file/2023/9/60559_0s.png)
Java内部类知识汇总
![](https://img.aspxhome.com/file/2023/0/61000_0s.png)
C#多线程实现异步接口
![](https://img.aspxhome.com/file/2023/5/116495_0s.jpg)
Java并发之不可思议的死循环详解
Android中banner的使用步骤
论C++的lambda是函数还是对象
Spring Boot 整合JPA 数据模型关联使用操作(一对一、一对多、多对多)
Android标题栏中添加返回按钮功能
Eclipse+Java+Swing+Mysql实现工资管理系统
![](https://img.aspxhome.com/file/2023/0/57960_0s.png)