在java后台判断两个文件是否是同一文件
2017-05-19 16:10
399 查看
1.计算MD5或SHA-1然后对比判断
2.直接判断内容是否相同
// 计算文件的 MD5 值 根据MD5值 判断文件是否是同一个文件 public static String getFileMD5(File file) { if (!file.isFile()) { return null; } MessageDigest digest = null; FileInputStream in = null; byte buffer[] = new byte[8192]; int len; try { digest =MessageDigest.getInstance("MD5"); in = new FileInputStream(file); while ((len = in.read(buffer)) != -1) { digest.update(buffer, 0, len); } BigInteger bigInt = new BigInteger(1, digest.digest()); return bigInt.toString(16); } catch (Exception e) { e.printStackTrace(); return null; } finally { try { in.close(); } catch (Exception e) { e.printStackTrace(); } } }
// 计算文件的 SHA-1 值 根据SHA-1值 判断文件是否是同一个文件 public static String getFileSha1(File file) { if (!file.isFile()) { return null; } MessageDigest digest = null; FileInputStream in = null; byte buffer[] = new byte[8192]; int len; try { digest =MessageDigest.getInstance("SHA-1"); in = new FileInputStream(file); while ((len = in.read(buffer)) != -1) { digest.update(buffer, 0, len); 9cb6 } BigInteger bigInt = new BigInteger(1, digest.digest()); return bigInt.toString(16); } catch (Exception e) { e.printStackTrace(); return null; } finally { try { in.close(); } catch (Exception e) { e.printStackTrace(); } } }
2.直接判断内容是否相同
public class IOOperation { public static void main(String[] args) { FileInputStream File1 = null; FileInputStream File2 = null; BufferedReader in = null; String sFile; if(args.length != 2) { System.out.println("The command line should be: java IOOperation testX.txt testX.txt"); System.out.println("X should be one of the array: 1, 2, 3"); System.exit(0); } try { File1 = new FileInputStream(args[0]); File2 = new FileInputStream(args[1]); try { if(File1.available() != File2.available()) { //长度不同内容肯定不同 System.out.println(args[0] + " is not equal to " + args[1]); } else { boolean tag = true; while( File1.read() != -1 && File2.read() != -1) { if(File1.read() != File2.read()) { tag = false; break; } } if(tag == true) System.out.println(args[0] + " equals to " + args[1]); else System.out.println(args[0] + " is not equal to " + args[1]); } } catch(IOException e) { System.out.println(e); } } catch (FileNotFoundException e) { System.out.println("File can't find.."); } finally { try { if(File1 != null) File1.close(); if(File2 != null) File2.close(); } catch (IOException e) { System.out.println(e); } } }
相关文章推荐
- Java 判断两个文件是否相同的两种方法
- Java-NowCoder-判断两个IP是否属于同一子网
- java 判断两个文件是否相同
- java判断两个文件的内容是否完全一样
- Java--判断两个文件是否相同
- Java判断两个路径对应的文件是否相同
- [java]用md5来判断两个文件是否完全相同 1. 前言
- Java判断两个路径对应的文件是否相同
- java 判断两个文件是否相同
- java如何判断一个linux下的文件是否为链接文件。
- Java判断文件目录以及文件是否存在
- Java判断文件是否完整
- JAVA读取中文文件,判断string中含有中文字符,判断某一个字符是否为中文字符
- 【WM】如何判断两个窗口是否由同一进程创建
- JAVA--第十周作业编写之一个Teacher类负责给出算术题目,随机给出两个整数并进行运算,并判断回答者的答案是否正确;编写一个GUI类ComputerFrame,回答者可以通过GUI看到题目并给出
- 【java常见问题】——如何判断文件是否为空?
- Java根据文件内容判断是否是图片
- 学习体会:在JAVA中如何判断两个对象是否相等
- java 创建文件夹 创建文件 判断文件夹是否存在。。。。。
- 判断两个文件是否完全相同