代码如下:
File file = new File("d:/1.dat");
FileInputStream fs = new FileInputStream(file);
BufferedInputStream bi = new BufferedInputStream(fs);
ByteArrayOutputStream bo = new ByteArrayOutputStream();
byte[] b = new byte[bi.available()];
int i;
while ((i = bi.read(b, 0, b.length)) != -1)
{
bo.write(b, 0, i);
}
bo.close();
System.out.print(Md5.MD5(new String(bo.toByteArray())));
public final static String MD5(String s)
{
char hexDigits[] = {‘0’, ‘1’, ‘2’, ‘3’, ‘4’, ‘5’, ‘6’, ‘7’, ‘8’, ‘9’, ‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’};
try
{
byte[] strTemp = s.getBytes();
MessageDigest mdTemp = MessageDigest.getInstance("MD5");
mdTemp.update(strTemp);
byte[] md = mdTemp.digest();
int j = md.length;
char str[] = new char[j * 2];
int k = 0;
for (int i = 0; i < j; i++)
{
byte byte0 = md[i];
str[k++] = hexDigits[byte0 >>> 4 & 0xf];
str[k++] = hexDigits[byte0 & 0xf];
}
return new String(str);
}
catch (Exception e)
{
return null;
}
}
Md5.MD5就是通过string生成md5编码.
后来在网上下载了一个看文件的md5编码的软件,和我出来的结果不一样.
查询一些资料,好像应该是读文件签名或者认证的md5,如果文件比较大,也不可能把所有的文件数据读到内存.
如果读文件认证的md5或者文件hashcode的md5