Here you can find the source of generateChecksum(String pType, String pInFile)
Parameter | Description |
---|---|
pType | type of checksum to generate (MD5/SHA1 etc) |
pInFile | file to checksum |
Parameter | Description |
---|---|
IOException | file access error |
public static String generateChecksum(String pType, String pInFile) throws IOException
//package com.java2s; /*//from w w w .ja v a 2 s .c om * Copyright 2014 The British Library/SCAPE Project Consortium * Author: William Palmer (William.Palmer@bl.uk) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class Main { private final static int BUFSIZE = 32768; /** * Generates a checksum for a file * @param pType type of checksum to generate (MD5/SHA1 etc) * @param pInFile file to checksum * @return A String with the format MD5:XXXXXX or SHA1:XXXXXX * @throws IOException file access error */ public static String generateChecksum(String pType, String pInFile) throws IOException { if (!new File(pInFile).exists()) throw new IOException("File not found: " + pInFile); MessageDigest md; try { md = MessageDigest.getInstance(pType.toUpperCase()); } catch (NoSuchAlgorithmException e) { return null; } FileInputStream input; try { input = new FileInputStream(pInFile); byte[] readBuffer = new byte[BUFSIZE]; int bytesRead = 0; while (input.available() > 0) { bytesRead = input.read(readBuffer); md.update(readBuffer, 0, bytesRead); } input.close(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } String hash = ""; for (byte b : md.digest()) hash += String.format("%02x", b); return hash; } /** * Generates a checksum for a file * @param pInFile file to checksum * @return A String with the format MD5:XXXXXX or SHA1:XXXXXX * @throws IOException file access error */ public static String generateChecksum(String pInFile) throws IOException { String type = "MD5"; return type + ":" + generateChecksum(type, pInFile); } }