判斷兩個檔案內容是否相同
阿新 • • 發佈:2018-11-11
package cn.bl.file; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; /** * 判斷兩個檔案是否內容完全相同 * @author BarryLee * @2018年11月1日@下午10:16:50 */ public class FileEquals { public static void main(String[] args) { File file1 = new File("E:/a/a.txt"); File file2 = new File("E:/a/a - 副本.txt"); String str1 = getMD5Str(file1); String str2 = getMD5Str(file2); System.out.println(str1.equals(str2)); } public static String getMD5Str(File file) { if(!file.isFile()) { System.out.println(file.getName()+"不是檔案"); return null; } InputStream in = null; try { MessageDigest digest = MessageDigest.getInstance("MD5"); in = new FileInputStream(file); byte[]bs = new byte[1024]; int len = -1; while((len=in.read(bs))!=-1) { digest.update(bs,0,len); } BigInteger bi = new BigInteger(1,digest.digest()); return bi.toString(16); } catch (NoSuchAlgorithmException e) { } catch (IOException e) { e.printStackTrace(); } finally { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } return null; } }