集册 Java实例教程 获取文件MD5

获取文件MD5

欢马劈雪     最近更新时间:2020-01-02 10:19:05

524
获取文件MD5

// Licensed under the Apache License, Version 2.0 (the "License");

//package com.nowjava;
/*
来 自*
 nowjava - 时代Java
*/

import java.io.File;

import java.io.FileInputStream;

import java.io.InputStream;

import java.security.MessageDigest;


public class Main {

    public static String getFileMD5(File file) {

        String str = "";

        try {

            str = getHash(file, "MD5");

        } catch (Exception e) {

            e.printStackTrace();
            /** 
             来自 n o w j a v a . c o m - 时  代  Java**/

        }

        return str;

    }


    private static String getHash(File file, String hashType)

            throws Exception {

        InputStream fis = new FileInputStream(file);

        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
展开阅读全文