aspose file tools*
The moose likes Beginning Java and the fly likes Comparing Two Files Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Comparing Two Files" Watch "Comparing Two Files" New topic
Author

Comparing Two Files

Bharadwaj Adepu
Ranch Hand

Joined: Dec 30, 2007
Posts: 99
How do i compare two files using Java.
What classes and Packages caon i use?


SCJP 1.5
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38348
    
  23
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

Joined: Dec 30, 2007
Posts: 99
I mean comparing the contents of the two files i.e. i want to know whether the two files are identical.
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 38348
    
  23
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

Joined: Jan 30, 2000
Posts: 18671
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.


"I'm not back." - Bill Harding, Twister
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Comparing Two Files