Here you can find the source of sha1(File sourceFile)
Parameter | Description |
---|---|
sourceFile | the original file or directory |
Parameter | Description |
---|---|
Exception | if any IOException of SecurityException occured |
public static String sha1(File sourceFile) throws Exception
//package com.java2s; //License from project: Open Source License import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.MessageDigest; public class Main { /**//from w w w. j av a 2 s . com * Computes the hash of a file or directory. * * @param sourceFile the original file or directory * @return an hex string representing the SHA1 hash of the file or directory. * @throws Exception if any IOException of SecurityException occured */ public static String sha1(File sourceFile) throws Exception { byte[] buffer = new byte[1024]; MessageDigest complete = MessageDigest.getInstance("SHA-1"); updateDigest(complete, sourceFile, buffer); byte[] bytes = complete.digest(); StringBuilder sb = new StringBuilder(); for (byte b : bytes) { sb.append(String.format("%02x", b)); } return sb.toString(); } private static void updateDigest(final MessageDigest digest, final File sourceFile, final byte[] buffer) throws IOException { if (sourceFile.isFile()) { try (InputStream fis = new FileInputStream(sourceFile)) { int numRead; do { numRead = fis.read(buffer); if (numRead > 0) { digest.update(buffer, 0, numRead); } } while (numRead != -1); } } else if (sourceFile.isDirectory()) { File[] files = sourceFile.listFiles(); if (files != null) { for (File file : files) { updateDigest(digest, file, buffer); } } } } }