/** * Copyright 2011 Oliver Buchtala * * This file is part of ndogen. * * ndogen is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * ndogen is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with ndogen. If not, see <http://www.gnu.org/licenses/>. */ package org.ndogen.watch; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.DigestInputStream; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; public class FileUtils { public static String readFile(String file) throws IOException { int len = (int) (new File(file)).length(); FileInputStream fis = new FileInputStream(file); byte buf[] = new byte[len]; fis.read(buf); fis.close(); return new String(buf); } public static String getFileHash(File file) throws IOException { MessageDigest md; try { md = MessageDigest.getInstance("MD5"); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } InputStream is = new FileInputStream(file); byte[] buf = new byte[1024]; try { is = new DigestInputStream(is, md); // read stream to EOF as normal... while(is.read(buf) > 0); } finally { is.close(); } byte[] digest = md.digest(); return new String(digest); } public static String getMD5(String s) throws NoSuchAlgorithmException { byte[] bytes = s.getBytes(); MessageDigest algorithm = MessageDigest.getInstance("MD5"); algorithm.reset(); algorithm.update(bytes); byte messageDigest[] = algorithm.digest(); StringBuffer hexString = new StringBuffer(); for (int i=0;i<messageDigest.length;i++) { hexString.append(Integer.toHexString(0xFF & messageDigest[i])); } return hexString.toString(); } public static boolean exists(String file) { return new File(file).exists(); } }