import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* 创建日期:Feb 24, 2011
* Title:
* Description:对本文件的详细描述,原则上不能少于50字
* @author
* @mender:(文件的修改者,文件创建者之外的人)
* @version 1.0
* Remark:认为有必要的其他信息
*/
public class MD5Util
{
/**
*
* 功能:获取指定路径下的文件的filePath
* 作者:
* 创建日期:Feb 24, 2011
* 修改者: mender
* 修改日期: modifydate
* @param filePath
* @return
*/
public static String getFileMD5(String filePath)
{
String strMd5="";
if(filePath!=null&&filePath.length()>0)
{
File file=new File(filePath);
if(file!=null&&file.isFile())
{
return getFileMD5(file);
}
else
{
System.err.println("指定路径下的文件不存在,或指定的路径指向的是一个目录!");
}
}
return strMd5;
}
/**
*
* 功能:获取指定的File对象的MD5值
* 作者:
* 创建日期:Feb 24, 2011
* 修改者: mender
* 修改日期: modifydate
* @param file
* @return
*/
public static String getFileMD5(File file)
{
String strMd5="";
File fileToCalaulate=file;
if(fileToCalaulate!=null)
{
try {
FileInputStream fis=new FileInputStream(fileToCalaulate);
MessageDigest md5 = MessageDigest.getInstance("MD5");
byte bufferArray[]=new byte[10240];
if(fis!=null)
{
int byteLength=fis.read(bufferArray);
while(byteLength!=-1)
{
md5.update(bufferArray,0,byteLength);
byteLength=fis.read(bufferArray);
}
byte md5ByteArray[]=md5.digest();
strMd5=byteArrayToHexString(md5ByteArray);
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return strMd5;
}
/**
*
* 功能:
* 作者:
* 创建日期:Feb 24, 2011
* 修改者: mender
* 修改日期: modifydate
* @param bArray
* @return
*/
public static String byteArrayToHexString(byte[] bArray)
{
String hexString=null;
/**
* 表示16进制的字符
*/
char hexChar[]={'0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F'};
byte byteArray[]=bArray;
/**
* 用于标示MD5的字符数组
*/
char md5Char[]=new char[32];
int j=0;
if(byteArray!=null&&byteArray.length>0)
{
for(int i=0;i<byteArray.length;i++)
{
byte tmpByte=byteArray[i];
int heightIndex=tmpByte>>>4&0xf;//取该字节的高4位,获取其16进制值
int lowIndex=tmpByte&0xf;//取该字节的低4位,获取其16进制值
md5Char[j++]=hexChar[heightIndex];
md5Char[j++]=hexChar[lowIndex];
}
hexString=new String(md5Char);
}
return hexString;
}
/**
*
* 功能:利用JDK5.0里提供的String.fromat函数对字节数组进行格式化,将其转换为16进制的字符串
* 作者:
* 创建日期:Feb 24, 2011
* 修改者: mender
* 修改日期: modifydate
* @param bArray
* @return
*/
public static String formatByteArrayToHexString(byte[] bArray)
{
byte byteArray[]=bArray;
StringBuffer strBuffer=new StringBuffer();
if(byteArray!=null&&byteArray.length>0)
{
for(int i=0;i<byteArray.length;i++)
{
strBuffer.append(String.format("%X", byteArray[i]));
}
}
return strBuffer.toString();
}
}