[Schmitzm-commits] r1476 - trunk/schmitzm-core/src/main/java/de/schmitzm/io

scm-commit@wald.intevation.org scm-commit at wald.intevation.org
Sun Jan 30 13:31:46 CET 2011


Author: alfonx
Date: 2011-01-30 13:31:46 +0100 (Sun, 30 Jan 2011)
New Revision: 1476

Modified:
   trunk/schmitzm-core/src/main/java/de/schmitzm/io/IOUtil.java
Log:
Moved Michael's md5hash method to IOUtils

Modified: trunk/schmitzm-core/src/main/java/de/schmitzm/io/IOUtil.java
===================================================================
--- trunk/schmitzm-core/src/main/java/de/schmitzm/io/IOUtil.java	2011-01-30 01:00:37 UTC (rev 1475)
+++ trunk/schmitzm-core/src/main/java/de/schmitzm/io/IOUtil.java	2011-01-30 12:31:46 UTC (rev 1476)
@@ -52,6 +52,8 @@
 import java.net.URLDecoder;
 import java.nio.channels.FileChannel;
 import java.nio.charset.Charset;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
 import java.util.Enumeration;
 import java.util.regex.Matcher;
 import java.util.regex.Pattern;
@@ -1395,7 +1397,6 @@
 
 	static public void unzipEntry(ZipFile zipfile, ZipEntry entry,
 			File outputDir) throws IOException {
-		System.out.println("next=" + entry.getName());
 
 		if (entry.isDirectory()) {
 			createDir(new File(outputDir, entry.getName()));
@@ -1488,4 +1489,55 @@
 		zipFile(delFile, zos, cutOff.getAbsolutePath().length());
 	}
 
+	/**
+	 * Returns a n md5 hash as a String for the given {@link File} parameter.
+	 * The file parameter may not point to a directory!
+	 * 
+	 * @throws IllegalArgumentException
+	 *             if File can not be read/found/etc
+	 */
+	public static String md5hash(File file) {
+		byte[] digest = null;
+		if (!file.exists() || file.isDirectory())
+			throw new IllegalArgumentException(
+					"Parameter must point to an existing file.");
+
+		try {
+
+			MessageDigest md5hash;
+			try {
+				md5hash = MessageDigest.getInstance("MD5");
+			} catch (NoSuchAlgorithmException e) {
+				throw new RuntimeException("Error while generating md5", e);
+			}
+			byte[] buffer = new byte[1024];
+			InputStream is;
+			is = new FileInputStream(file);
+			try {
+				int numRead;
+				do {
+					numRead = is.read(buffer);
+					if (numRead > 0) {
+						md5hash.update(buffer, 0, numRead);
+					}
+				} while (numRead != -1);
+			} finally {
+				is.close();
+			}
+			digest = md5hash.digest();
+
+			String result = "";
+			if (digest != null) {
+				for (int i = 0; i < digest.length; i++) {
+					result += Integer.toString((digest[i] & 0xff) + 0x100, 16)
+							.substring(1);
+				}
+			}
+			return result;
+		} catch (IOException e) {
+			throw new IllegalArgumentException("Failed to md4 hash: "
+					+ file.getAbsolutePath(), e);
+		}
+
+	}
 }



More information about the Schmitzm-commits mailing list