A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 柳雷 中级黑马   /  2012-7-26 14:14  /  992 人查看  /  0 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

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值么?那如果文件很大的话,会不会很慢么?

0 个回复

您需要登录后才可以回帖 登录 | 加入黑马