import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
public class HashUtil {
private static char hexChar[] = { '0', '1', '2', '3', '4', '5', '6', '7',
'8', '9', 'a', 'b', 'c', 'd', 'e', 'f' };
public HashUtil() {
}
public static String getFileMD5(String filename) {
String str = "";
try {
str = getHash(filename, "MD5");
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
public static String getFileSHA1(String filename) {
String str = "";
try {
str = getHash(filename, "SHA1");
} catch (Exception e) {
e.printStackTrace();
}
return str;
}
private static String getHash(String fileName, String hashType)
throws Exception {
InputStream fis = new FileInputStream(fileName);
byte buffer[] = new byte[1024];
MessageDigest md5 = MessageDigest.getInstance(hashType);
for (int numRead = 0; (numRead = fis.read(buffer)) > 0;) {
md5.update(buffer, 0, numRead);
}
fis.close();
return toHexString(md5.digest());
}
private static String toHexString(byte b[]) {
StringBuilder sb = new StringBuilder(b.length * 2);
for (int i = 0; i < b.length; i++) {
sb.append(hexChar[(b[i] & 0xf0) >>> 4]);
sb.append(hexChar[b[i] & 0xf]);
}
return sb.toString();
}
public static void main(String[] args) {
System.out.println(HashUtil.getFileSHA1("D:\\upload\\file\\haha.txt"));
}
关于这个工具类,谁能给我解释下,那个for循环的原理啊?是根据文件流来判断hash值么?那如果文件很大的话,会不会很慢么? |
|