预先一个需求,要把文件存储至redies缓存中,但是考虑到key值得问题。我出的方案是将文件的内容生成的MD5码当做key值,当文件内容一样时,生成的MD5也一样,就不用重新存储了。。。。。
废话不多说了,直接撸代码吧
/**
* pdf2md5Util.java
* admin.utils
*/
package admin.utils;
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.nutz.log.Log;
import org.nutz.log.Logs;
/**
* pdf内容转成Md5码的工具包
*/
public class Pdf2md5Util {
private static final Log log = Logs.get();
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) {
log.info(e.getMessage());
} catch (NoSuchAlgorithmException e) {
log.info(e.getMessage());
} catch (IOException e) {
log.info(e.getMessage());
} finally {
try {
if (null != fis) {
fis.close();
}
} catch (IOException e) {
}
}
return null;
}
//快速转换 十六进制数组的字节数组
public static String getMD5Checksum(String filename) {
if (!new File(filename).isFile()) {
log.info("Error: " + filename + " is not a valid file.");
return null;
}
byte[] b = createChecksum(filename);
if (null == b) {
log.info("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();
}
//===================================华丽分割线================================================
/**
* 测试
* @Date 2018年4月21日
* @author gyp
* @param args(这里描述每个参数,如果有返回值描述返回值,如果有异常描述异常)
*/
public static void main(String args[]) {
try {
long beforeTime = System.currentTimeMillis();
//String path = "C:\\Users\\Desktop\\测试文件\\1.pdf";
String path = "C:\\Users\\Desktop\\测试文件\\2.pdf";
//当两个pdf内容相等时,生成的MD5码一样
String before = "ae058327a03fe8260117c3f345657aeb".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) {
System.out.println("出现异常:" + e.getMessage());
}
}
}