get File SHA 512 - Java File Path IO

Java examples for File Path IO:File Hash

Description

get File SHA 512

Demo Code

// Licensed under the Apache License, Version 2.0 (the "License");
//package com.java2s;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;

public class Main {
    public static String getFileSHA512(File file) {
        String str = "";
        try {//from w  w  w  .jav  a 2  s  . c  o  m
            str = getHash(file, "SHA-512");
        } 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];
        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();
        for (int i = 0; i < b.length; i++) {
            sb.append(Integer.toHexString(b[i] & 0xFF));
        }
        return sb.toString();
    }
}

Related Tutorials