这里要获取文件的md5值,主要是做文件管理系统的时候需要用到,获得文件的md5值,然后和自己的数据库比对,如果已经存在该文件,则不用再上传该文件,只是把相关的文件信息存储到对应的数据库中。像百度云盘和QQ聊天发送文件得时候的秒传,就是这样实现的。
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.math.BigInteger;
import java.security.MessageDigest;
/**
*
* @author canye
* @decription this is a class to get a md5 value of file
* @date 2017年3月7日
*/
public class MD5Demo {
/**
* @param args
*/
public static void main(String[] args) {
String md5 = getMD5ValueOfFile("F:\\logo\\cc.gif");
System.out.println(md5);
}
/**
* 获取文件的md5值
* @param fileName 文件名
* @return
*/
public static String getMD5ValueOfFile(String fileName){
//创建文件对象
File file = new File(fileName);
//判断文件是否存在,且是一个文件
if(!(file.exists()&&file.isFile())){
System.out.println("File is not correct!");
return "error";
}
//定义一个文件输入流对象
FileInputStream inputStream = null;
//定义一个信息摘要对象
MessageDigest digest = null;
try {
//实例化文件输入流
inputStream = new FileInputStream(file);
//实例化信息摘要,采用MD5算法
digest = MessageDigest.getInstance("MD5");
//定义一个字节数组
byte[] buffer = new byte[1024];
//定义一个length变量
int length = -1;
while((length = inputStream.read(buffer,0,buffer.length)) != -1){
digest.update(buffer, 0, length);//更新摘要
}
} catch (Exception e) {
e.printStackTrace();
return "error";
}finally{//释放资源
if(inputStream != null){
try {
inputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
//生成MD5值
BigInteger bigInteger = new BigInteger(1, digest.digest());//1表示得到的结果为正数
String md5 = bigInteger.toString(16);//16表示把数值转换为16进制
return md5;
}
}