天天看点

java 获取文件MD5值

java 获取文件MD5值

/** 

     * get md5 of one file:hex string,test ok! 

     *  

     * @param file 

     * @return 

     */  

    public static string getfilemd5(file file) {  

        if (!file.exists() || !file.isfile()) {  

            return null;  

        }  

        messagedigest digest = null;  

        fileinputstream in = null;  

        byte buffer[] = new byte[1024];  

        int len;  

        try {  

            digest = messagedigest.getinstance("md5");  

            in = new fileinputstream(file);  

            while ((len = in.read(buffer, 0, 1024)) != negative_one) {  

                digest.update(buffer, 0, len);  

            }  

            in.close();  

        } catch (exception e) {  

            e.printstacktrace();  

        biginteger bigint = new biginteger(1, digest.digest());  

        return bigint.tostring(16);  

    }  

    /*** 

     * get md5 of one file!test ok! 

     * @param filepath 

    public static string getfilemd5(string filepath) {  

        file file = new file(filepath);  

        return getfilemd5(file);  

    /** 

     * md5 encrypt,test ok 

     * @param data 

     * @return byte[] 

     * @throws exception 

    public static byte[] encryptmd5(byte[] data) throws exception {  

        messagedigest md5 = messagedigest.getinstance(systemutil.key_md5);  

        md5.update(data);  

        return md5.digest();  

    public static byte[] encryptmd5(string data) throws exception {  

        return encryptmd5(data.getbytes(systemutil.charset_iso88591));  

     * compare two file by md5 

     * @param file1 

     * @param file2 

    public static boolean issamemd5(file file1,file file2){  

        string md5_1=systemutil.getfilemd5(file1);  

        string md5_2=systemutil.getfilemd5(file2);  

        return md5_1.equals(md5_2);  

     * @param filepath1 

     * @param filepath2 

    public static boolean issamemd5(string filepath1,string filepath2){  

        file file1=new file(filepath1);  

        file file2=new file(filepath2);  

        return issamemd5(file1, file2);  

 测试(使用junit):

java 获取文件MD5值

@test  

    public void test_getfilemd5() throws exception{  

        string filepath="d:\\download\\3_尚学堂_uml概览.avi";  

//      file file=new file(filepath);  

        string md5_1=systemutil.getfilemd5(filepath);  

        system.out.println(md5_1);  

        byte[]bytes=fileutils.readbytes4file(filepath);  

        byte[]md5=systemutil.encryptmd5(bytes);  

        string md5_2=systemutil.tohexstring(md5);  

        system.out.println(md5_2);  

        assert.assertequals(md5_1, md5_2);