`
coach
  • 浏览: 382882 次
  • 性别: Icon_minigender_2
  • 来自: 印度
社区版块
存档分类
最新评论

MD5验证器

阅读更多
import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Digest
{

    /**
     * 获取指定文件的md5值。
     * 
     * @param path 待验证的文件名
     */
    public static String checkMD5(String path)
    {
        StringBuilder sb = new StringBuilder();
        try
        {
            MessageDigest md5 = MessageDigest.getInstance("MD5");// 生成MD5类的实例
            File file = new File(path); // 创建文件实例,设置路径为方法参数
            FileInputStream fs = new FileInputStream(file);
            BufferedInputStream bi = new BufferedInputStream(fs);
            ByteArrayOutputStream bo = new ByteArrayOutputStream();
            byte[] b = new byte[bi.available()]; // 定义字节数组b大小为文件的不受阻塞的可访问字节数
            // int i;
            // 将文件以字节方式读到数组b中
            while ((bi.read(b, 0, b.length)) != -1)
            {
            }
            md5.update(b);// 执行MD5算法
            for (byte by : md5.digest())
            {
                sb.append(String.format("%02X", by));// 将生成的字节MD5值转换成字符串
            }
            bo.close();
            bi.close();
        }
        catch (NoSuchAlgorithmException e)
        {
            e.printStackTrace();
            return null;
        }
        catch (IOException e)
        {
            return null;
        }

        return sb.toString();// 返回MD5值
    }

    public static void main(String[] args) throws Exception
    {
        String md5 = checkMD5("c:\\MM.MP3");
        System.out.println(md5);
    }
}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics