Win a copy of The Java Performance Companion this week in the Performance forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Comparing Two Files

 
Bharadwaj Adepu
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
How do i compare two files using Java.
What classes and Packages caon i use?
 
Campbell Ritchie
Sheriff
Pie
Posts: 49445
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Don't understand the problem. Do you mean comparing the sizes, contents or what? Have you been through the methods in the File class? Would you have to read the entire contents into a String and compare the two String?
 
Bharadwaj Adepu
Ranch Hand
Posts: 99
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I mean comparing the contents of the two files i.e. i want to know whether the two files are identical.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49445
62
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If they are text files, try:
Use a Scanner to iterate through the files.
Whenever you get a new line append it to a StringBuilder.
When myScanner.hasNext() shows false you can stop.

The StringBuilders won't show equal, but you can get them into a String and test like this:That's one way to do it.
 
Jim Yingst
Wanderer
Sheriff
Posts: 18671
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I would first check if the lengths are equal, and if not, return false. Then open two FileInputStreams wrapped with BufferedInputStreams, one for each file. Then write a loop that reads one byte from each file, and returns false if the bytes are not equal. Keep looping until one the end of a file is reached. (You already know they're the same length at this point, so you should reach the end of both files simultaneously.) If you reach the end successfully without returning false, then you can return true instead - all the bytes must be equal.

Note that this technique works equally well regardless of whether you're using text files or binary files. It just tests whether they are exactly equal, or not.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic