Advertisement
Guest User

Untitled

a guest
Apr 26th, 2017
62
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. public static boolean contentEquals(File file1, File file2) throws IOException {
  2. boolean file1Exists = file1.exists();
  3. if (file1Exists != file2.exists()) {
  4. return false;
  5. }
  6.  
  7. if (!file1Exists) {
  8. // two not existing files are equal
  9. return true;
  10. }
  11.  
  12. if (file1.isDirectory() || file2.isDirectory()) {
  13. // don't want to compare directory contents
  14. throw new IOException("Can't compare directories, only files");
  15. }
  16.  
  17. if (file1.length() != file2.length()) {
  18. // lengths differ, cannot be equal
  19. return false;
  20. }
  21.  
  22. if (file1.getCanonicalFile().equals(file2.getCanonicalFile())) {
  23. // same file
  24. return true;
  25. }
  26.  
  27. InputStream input1 = null;
  28. InputStream input2 = null;
  29. try {
  30. input1 = new FileInputStream(file1);
  31. input2 = new FileInputStream(file2);
  32. return contentEquals(input1, input2);
  33.  
  34. } finally {
  35. input1.close();
  36. input2.close();
  37. }
  38. }
  39.  
  40.  
  41. public static boolean contentEquals(InputStream input1, InputStream input2)
  42. throws IOException {
  43. if (!(input1 instanceof BufferedInputStream)) {
  44. input1 = new BufferedInputStream(input1);
  45. }
  46. if (!(input2 instanceof BufferedInputStream)) {
  47. input2 = new BufferedInputStream(input2);
  48. }
  49.  
  50. int ch = input1.read();
  51. while (-1 != ch) {
  52. int ch2 = input2.read();
  53. if (ch != ch2) {
  54. return false;
  55. }
  56. ch = input1.read();
  57. }
  58.  
  59. int ch2 = input2.read();
  60. return (ch2 == -1);
  61. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement