5

I have two properties files that contain information. I would like to diff them to see if they are the same. However, in properties files, unless you specify an order to output they write to a file in a different order. I don't have access to the code just these files. How can I check if their contents are the same?

For example,

File1    File2
a        e
b        c
c        a
d        d
e        b

How can I detect that these two files would be the same? a-e represent strings of information

Thanks!

Diego
  • 16,830
  • 8
  • 34
  • 46

4 Answers4

9

You have already accepted an answer, but I'll add this anyway, just to point out that there's an easier way (assuming you are talking about normal Java properties files).

You actually don't have to do any sorting, line-by-line comparison etc. yourself, because equals() in java.util.Properties has been implemented smartly and does what one would expect. In other words, "know and use the libraries", as Joshua Bloch would say. :-)

Here's an example. Given file p1.properties:

a = 1
b = 2

and p2.properties:

b = 2
a = 1

...you can just read them in and compare them with equals():

Properties props1 = new Properties();
props1.load(new FileReader("p1.properties"));    
Properties props2 = new Properties();
props2.load(new FileReader("p2.properties"));

System.out.println(props1.equals(props2)); // true
Community
  • 1
  • 1
Jonik
  • 80,077
  • 70
  • 264
  • 372
  • 1
    Also, this method guarantees that comments and blank lines are ignored, as are differences in formatting (x=aa versus x="aa"). – Mike Baranczak Nov 21 '10 at 16:56
  • 1
    +1 - this is a better answer than mine (I was answering from a generic standpoint, as I'm writing in C++ rather than Java on a day-to-day basis at the moment) – Stuart Golodetz Nov 21 '10 at 16:56
3

Read them in, sort them, then run through them alongside each other and compare them. The sorting could be accomplished by inserting them into a sorted data structure, incidentally.

Stuart Golodetz
  • 20,238
  • 4
  • 51
  • 80
1

Sort the contents and then compare line by line.

milan
  • 2,355
  • 2
  • 23
  • 38
-1

You could do that on the command line. Your two files are File1 and File2.

$ sort File1 > sorted_File1

$ sort File2 > sorted_File2

And then use a diff utility like meld (which is graphical diff program).

$ meld sorted_File1 sorted_File2

varunl
  • 19,499
  • 5
  • 29
  • 47