本例以Windows, JDK1.7 为基础,来演示Java 对文件校验码的生成。
通常我们在校验两个个文件是否是相同时,都会对比文件的MD5和SHA1值,接下来演示对文件的MD5和SHA1码的生产。
这里使用MessageDigest 来处理, 分别获取MessageDigest类的两个实例
1 2
| MessageDigest md = MessageDigest.getInstance("SHA1"); MessageDigest md = MessageDigest.getInstance("MD5");
|
示例代码
FileUniqueCheck.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112
| package com.devnp.io;
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 FileUniqueCheck {
public static void main(String[] args) { File file = new File("D:\\Person-Test\\5.pdf"); System.out.println("File MD5 Value : " + generateMD5(file)); System.out.println("File SHA1 Value : " + generateSHA(file)); } public static String generateMD5(File file){ StringBuffer sb = new StringBuffer(); MessageDigest md = null; FileInputStream fis = null ; try { md = MessageDigest.getInstance("MD5"); fis = new FileInputStream(file); byte[] dataBytes = new byte[1024];
int nread = 0;
while ((nread = fis.read(dataBytes)) != -1) { md.update(dataBytes, 0, nread); };
byte[] mdbytes = md.digest();
for (int i = 0; i < mdbytes.length; i++) { sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { if(fis != null) fis.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString() ; } public static String generateSHA(File file){ StringBuffer sb = new StringBuffer(); MessageDigest md = null; FileInputStream fis = null ; try { md = MessageDigest.getInstance("SHA1"); fis = new FileInputStream(file); byte[] dataBytes = new byte[1024];
int nread = 0;
while ((nread = fis.read(dataBytes)) != -1) { md.update(dataBytes, 0, nread); };
byte[] mdbytes = md.digest();
for (int i = 0; i < mdbytes.length; i++) { sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100, 16).substring(1)); } } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ try { if(fis != null) fis.close(); } catch (IOException e) { e.printStackTrace(); } } return sb.toString() ; }
}
|
运行结果:
1 2
| File MD5 Value : 781532b94a6b5314ab1903d9c3ad93f2 File SHA1 Value : bdff05200ce2ed0a9aaa63555cb04049303a7228
|
Author:
Darren Du
License:
Copyright (c) 2019 MIT LICENSE