Java生成文件hash值
生活随笔
收集整理的這篇文章主要介紹了
Java生成文件hash值
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
Java生成文件hash值(通過傳入file或者InputStream)
package com.hczy.syncdata.common.util;import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.security.MessageDigest;public class FileHahUtil {/*** 計算文件hash值*/public static String hashFile(File file) throws Exception {FileInputStream fis = null;String sha256 = null;try {fis = new FileInputStream(file);MessageDigest md = MessageDigest.getInstance("SHA-256");byte buffer[] = new byte[1024];int length = -1;while ((length = fis.read(buffer, 0, 1024)) != -1) {md.update(buffer, 0, length);}byte[] digest = md.digest();sha256 = byte2hexLower(digest);} catch (Exception e) {e.printStackTrace();throw new Exception("計算文件hash值錯誤");} finally {try {if (fis != null) {fis.close();}} catch (IOException e) {e.printStackTrace();}}return sha256;}private static String byte2hexLower(byte[] b) {String hs = "";String stmp = "";for (int i = 0; i < b.length; i++) {stmp = Integer.toHexString(b[i] & 0XFF);if (stmp.length() == 1) {hs = hs + "0" + stmp;} else {hs = hs + stmp;}}return hs;}public static String md5HashCode(InputStream fis) { try { //拿到一個MD5轉換器,如果想使用SHA-1或SHA-256,則傳入SHA-1,SHA-256 MessageDigest md = MessageDigest.getInstance("MD5"); //分多次將一個文件讀入,對于大型文件而言,比較推薦這種方式,占用內(nèi)存比較少。byte[] buffer = new byte[1024]; int length = -1; while ((length = fis.read(buffer, 0, 1024)) != -1) { md.update(buffer, 0, length); } fis.close();//轉換并返回包含16個元素字節(jié)數(shù)組,返回數(shù)值范圍為-128到127byte[] md5Bytes = md.digest();BigInteger bigInt = new BigInteger(1, md5Bytes);//1代表絕對值 return bigInt.toString(16);//轉換為16進制} catch (Exception e) { e.printStackTrace(); return ""; } } public static void main(String[] args) {try {File file = new File("D:\\file\\practice\\Downloads.rar");File file1 = new File("D:\\file\\practice\\into\\Downloads.rar");File file2 = new File("D:\\file\\practice\\into\\Downloads(1).rar"); // System.out.println(md5HashCode(new FileInputStream(file))); // System.out.println(md5HashCode(new FileInputStream(file)).equals(md5HashCode(new FileInputStream(file))) ); // System.out.println(hashFile(file)); // System.out.println(hashFile(file).equals(hashFile(file1))); // System.out.println(hashFile(file).equals(hashFile(file2)));File file3 = new File("D:\\file\\practice\\into\\Google.rar");String md5HashCode = FileHahUtil.md5HashCode(new FileInputStream(file));System.out.println(md5HashCode);} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}}}
知是行之始,行是知之成
總結
以上是生活随笔為你收集整理的Java生成文件hash值的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: javascript 中怎么判断为数字类
- 下一篇: 雄安新区 行政范围经纬度坐标