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

获取文件SHA

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

528
获取文件SHA

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

//package com.nowjava;

import java.io.File;

import java.io.FileInputStream;/** n o w    j a v a  . c o m 提供 **/

import java.io.InputStream;

import java.security.MessageDigest;


public class Main {

    public static String getFileSHA1(File file) {

        String str = "";

        try {

            str = getHash(file, "SHA1");

        } catch (Exception e) {

            e.printStackTrace();

        }

        return str;

    }


    private static String getHash(File file, String hashType)

            throws Exception {

        InputStream fis = new FileInputStream(file);

        byte buffer[] = new byte[1024];
        /*来自 
         时 代 J a v a - N o w J a v a . c o m*/

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