JAVA 生成文件的MD5码

 下面的代码是自己写的:

/**
 * Copyright 2012
 *
 * All right reserved
 * 
 * Created on 2012-8-31下午5:43:58
 */
package com.test.md5;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

import org.apache.log4j.Logger;

/**
 * 
 * @author xuepeng
 * 
 */
public class MD5Checksum {
	private static Logger LOGGER = Logger.getLogger(MD5Checksum.class);

	private static byte[] createChecksum(String filename) {
		InputStream fis = null;
		try {
			fis = new FileInputStream(filename);
			byte[] buffer = new byte[1024];
			MessageDigest complete = MessageDigest.getInstance("MD5");
			int numRead = -1;

			while ((numRead = fis.read(buffer)) != -1) {
				complete.update(buffer, 0, numRead);
			}
			return complete.digest();
		} catch (FileNotFoundException e) {
			LOGGER.error(e.getMessage(), e);
		} catch (NoSuchAlgorithmException e) {
			LOGGER.error(e.getMessage(), e);
		} catch (IOException e) {
			LOGGER.error(e.getMessage(), e);
		} finally {
			try {
				if (null != fis) {
					fis.close();
				}
			} catch (IOException e) {
				LOGGER.error(e.getMessage(), e);
			}
		}
		return null;

	}

	// see this How-to for a faster way to convert
	// a byte array to a HEX string
	public static String getMD5Checksum(String filename) {
	
			if (!new File(filename).isFile()) {
				LOGGER.error("Error: " + filename
						+ " is not a valid file.");
				return null;
			}
			byte[] b = createChecksum(filename);
			if(null == b){
				LOGGER.error("Error:create md5 string failure!");
				return null;
			}
			StringBuilder result = new StringBuilder();

			for (int i = 0; i < b.length; i++) {
				result.append(Integer.toString((b[i] & 0xff) + 0x100, 16)
						.substring(1));
			}
			return result.toString();

	}

	public static void main(String args[]) {
		try {
			long beforeTime = System.currentTimeMillis();
			String path = "C:\\Users\\user\\Desktop\\work_shedule.txt";
			String before = "999E42920C54CF7D66190731CD54F0E6".toLowerCase();
			String md5 = getMD5Checksum(path);
			System.out.println(md5);
			System.out.println(md5.equals(before));
			
			File file = new File(path);
			
			System.out.println(path+ "'s size is : " +file.length()+" bytes, it consumes " + (System.currentTimeMillis() - beforeTime) + " ms.");
		} catch (Exception e) {
			LOGGER.error(e.getMessage(), e);
		}
	}
}

 其实还有方便的MD5生成方法,就是采用apache提供的开源项目 commons-codec.jar 自带的MD5生成。

如:

File file = new File(fileName);
String md5 = DigestUtils.md5Hex(new FileInputStream(file));

 

附件中,我附带了一个方便日常生成MD5的jar,用来进行MD5的生成。

 

 

=========================== Google Guava ===============

import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;

import java.io.File;

public class HashingExample {

    public static void main(String[] args) throws Exception {
        print();
        File file = new File(
                "D:/test/FileCopy.java");
        
        HashCode hashCode = Files.hash(file, Hashing.md5());
        System.out.println(hashCode.toString());
    }

}

 

import com.google.common.hash.HashCode;
import com.google.common.hash.Hashing;
import com.google.common.io.Files;    
/**
     * <pre>
     *  得到指定文件的MD5
     * @param file 文件
     * @param upper 是否大写
     * @return file文件的MD5
     * @throws IOException
     * </pre>
     */
    public static String createMd5(File file, boolean upper) throws IOException {
        HashCode hashCode = Files.hash(file, Hashing.md5());
        return upper ? hashCode.toString().toUpperCase() : hashCode.toString();
    }

 有的时候我们不仅仅要对文件做MD5,也需要对字符串String进行MD5操作。下面的方法使用Guava写了一个生成字符串MD5的方法。

    /**
     * <pre>
     * @param charSequence
     * @param charset
     * @param upper
     * @return 生成的MD5
     * </pre>
     */
    public static String createMD5(CharSequence charSequence, Charset charset,
            boolean upper) {
        Preconditions.checkNotNull(charSequence, "charSequence is null");
        Preconditions.checkNotNull(charset, "charset is null");

        String md5 = Hashing.md5().newHasher().putString(charSequence, charset)
                .hash().toString();
        return upper ? md5.toUpperCase() : md5;
    }

 示例:

        String md5 = createMD5("hello", Charsets.UTF_8, true);
        System.out.println(md5);//5D41402ABC4B2A76B9719D911017C592

 

你可能感兴趣的:(java)