一般来说定长度输出只需要用hash方法就可以了,不过有时候需要用md5的值来进行一些特别的处理工作,所以要用到它,自己写md5比较麻烦,所以可以用java.security包里面的东西。以下是网上搜到的一个范例:
- public class HashUtils {
- /**
- * 文件SHA-1 Hash值生成器
- *
- * @param in
- * @return
- * @throws Exception
- */
- public static String generateFileSHA1(String fileUrl) throws Exception {
- InputStream in = new BufferedInputStream(new FileInputStream(fileUrl));
- MessageDigest md = MessageDigest.getInstance("SHA-1");
- byte[] buffer = new byte[8192];
- int length = -1;
- while ((length = in.read(buffer)) != -1) {
- md.update(buffer, 0, length);
- }
- return StringBytesTransformUtils.bytesToHexString(md.digest());
- }
- /**
- * 文件MD5 Hash值生成器
- *
- * @param fileUrl
- * @return
- * @throws Exception
- */
- public static String generateFileMD5(String fileUrl) throws Exception {
- InputStream in = new BufferedInputStream(new FileInputStream(fileUrl));
- MessageDigest md = MessageDigest.getInstance("MD5");
- byte[] buffer = new byte[8192];
- int length = -1;
- while ((length = in.read(buffer)) != -1) {
- md.update(buffer, 0, length);
- }
- return StringBytesTransformUtils.bytesToHexString(md.digest());
- }
- }
没有评论:
发表评论