CompareTo method to compare files

I have to compare each line from two files and say whether the lines are different or not. I don't exactly understand how to use the compareTo method in this type of situation. I'd appreciate any help.
import java.util.*;
import java.io.*;
import java.net.*;
import java.util.StringTokenizer;
public class FileComparer
public static void main (String[] args)
String line, file="http://condor.depaul.edu/~jpetlick/extra/224/display.txt";
String line2, file2="http://condor.depaul.edu/~jpetlick/extra/224/display2.txt";
int lineCount = 0, wordCount = 0, lineCounter = 0;
try
URL URLfile = new URL (file);
InputStream input = URLfile.openStream();
BufferedReader buffer = new BufferedReader(new InputStreamReader(input));
line = buffer.readLine();
URL URLfile2 = new URL (file2);
InputStream input2 = URLfile2.openStream();
BufferedReader buffer2 = new BufferedReader(new InputStreamReader(input2));
line2 = buffer2.readLine();
while (line != null)
if (line != line2)
System.out.println("at Line " + lineCounter);
System.out.println("DISPLAY.TXT " + line);
System.out.println("DISPLAY2.TXT " + line2);
lineCounter++;
StringTokenizer st = new StringTokenizer(line);
wordCount += st.countTokens();
lineCount++;
line = buffer.readLine();
line2 = buffer2.readLine();
System.out.println("\nA total of " + lineCounter + " were different between DISPLAY.TXT and DISPLAY2.TXT");
System.out.println("DISPLAY.TXT contains:");
System.out.println("\nTotal number of lines: " + lineCount);
System.out.println("Total number of words: " + wordCount);
catch (FileNotFoundException exception)
System.out.println("The file " + file + " was not found.");
catch (IOException exception)
System.out.println(exception);
}

Change the lineif (line != line2)to if (!line.equals( line2))since strings are immutable in java "line != line2" will alwais evaluate to false in your case.
equals actually compares the contents of the string.
Kurt.

Similar Messages

  • Understanding Comparable and the compareTo( ) method

    I have a Contact object which lists a person's information for a "phone book" program.
    I am trying to sort the Contact objects in a Vector by way of their last name fields.
    I am having a hell of a time trying to use this compareTo( ) method.
    I'm really struggling with understanding how to go about making the method work with a comparison. Most of the examples which I find compare "numbers' and not strings which make it more difficult to understand.
    I have implimented the comparable Interface at the start of my class. To sort my Vector, I'm attempting to use the compareTo( ) method to determine which Last name field has the lower value. I keep going back and forth working through the error messages I receive and I'm just stumped trying to figure out how to get this thing to work. Can someone please point out the mistakes without writing too much code? I don't want someone to do the work for me. Here is the code:
    import java.io.*;
    import java.util.*;
    class PhoneBook implements Comparable{
         private static Vector v = new Vector();
         private static Iterator iter = v.iterator();
         private static int num, index;
         private static Contact firstContact, secondContact, temp;  //"static" to be referenced from main
         public static void main(String arg[])throws Exception {
              Contact c;
              String str;
              BufferedReader br = new BufferedReader(
          new InputStreamReader(
               new FileInputStream(
                                           new File("contacts.txt"))));
              while((str = br.readLine()) != null){
               v.add(c= new Contact(br.readLine()));
               num = v.size();
               for(int i=0; i < num; i++){
          firstContact = (Contact)v.elementAt(i);
               if(v.elementAt(++i) == null)
                    break;
               else
                    secondContact = (Contact)v.elementAt(++i);
               index = compareTo(firstContact);
               if(index == 1){
                       temp = (Contact)v.elementAt(i);
                       v.setElementAt(v.elementAt(++i), i);
                       v.setElementAt(temp, ++i);
              public static int compareTo(Object person){
         int x = ((Contact)person).getLName().compareTo(secondContact.getLName());
         return x;
    }yet still I get the following compiler error:
    PhoneBook.java:4: compareTo(java.lang.Object) in PhoneBook cannot implement compareTo(java.lang.Object) in java.lang.Comparable; compareTo(java.lang.Object) and compareTo(java.lang.Object) are static
    class PhoneBook implements Comparable{
    ^
    1 error

    You are pretty close here except for one incorrect basic assumption. Your compiler error is because you are trying to implement compareTo() with a static method. However, this is irrelevant because it is not the PhoneBook class that should implement Comparable, but the Contact class.
    The idea is that other functions can call the compareTo() method on an instance of Contact and pass a reference to a second instance. Based on the result, the relative sort order of the two objects can be determined.
    e.g.Contact c1 = new Contact("Smith", "John");
    Contact c2 = new Contact("Jones", "Alan");
    int x = c1.compareTo(c2);In your example, you can implement compareTo() to use the corresponding method in String. For compatibility, you should also implement equals().
    public class Contact implements Comparable {
       public int compareTo(Object otherContact) {
           Contact otherC = (Contact) otherContact;  // could throw exception
           return getLName().compareTo(otherC.getLName());
       public boolean equals(Object otherContact) {
           Contact otherC = (Contact) otherContact;  // could throw exception
           return getLName().equals(otherC.getLName());
    } // end of class Contact I haven't compiled or tested the above code nor does it deal with exceptions (e.g. otherContact is not an instance of Contact) - I'll leave that to you! You'll also need to change your PhoneBook sort routine to invoke firstContact.compareTo(secondContact)
    FYI - I understand that this is an academic exercise and so you may need to code the sort yourself, but once Contact implements Comparable, you could sort the Vector using standard Java methods. Check out java.util.Collections - there is a method that will perform your sort in one line of code.
    Good Luck.

  • I must be losing my mind, Integer  not having a compareTo method?

    import java.util.Comparator;
    @SuppressWarnings("hiding")
    public class IntComparator<Integer> implements Comparator<Integer>
    @Override
    public int compare(Integer o1, Integer o2)
         o1.compareTo(o2);
    Eclipse is claiming that the Integer class does not have a compareTo(Integer) method.

    >
    @Override
    public int compare(Integer o1, Integer o2)
    Eclipse is claiming that the Integer class does not have a compareTo(Integer) method.It will be complaining that Integer does not have a compare method, the specific method you are trying to override that does not exist.
    However the Integer class does have a compareTo() method that you can override, refer to the API
    Mel

  • Compare file contents

    Usually I take my photos in RAW format, and a matching jpeg is produced automatically by the camera software. The file names are identical except for the extension. Occasionally however for speed of working I will take some photos on the card in jpeg only -no matching RAW.
    I have a workflow that separates the RAW and jpeg files into separate folders, but I can't seem to find a method to compare folder contents so as to easily and quickly identify the "lone jpegs" (i.e. those that have no matching RAW). The comparison could of course be done before or after separation - whichever is easiest.
    Anyone tried this or similar - it seems to be not currently possible (a glaring omission IMO) but maybe there's a work round that someone's found and would share?
    Thanks in advance for any responses!

    I don't know about automator, but it's an easy one for the shell:
    cohi@tigger:/tmp> ls raw
    1.raw 2.raw 4.raw
    cohi@tigger:/tmp> ls jpg
    1.jpg 2.jpg 3.jpg 4.jpg
    cohi@tigger:/tmp> ( find jpg -name "*.jpg" ; find raw -name "*.raw" ) | sed 's/raw/jpg/g' | sort | uniq -c | grep " 1" | cut -b 9-
    jpg/3.jpg

  • Overriding compareTo method for ints

    I'm having a problem writing the overloaded compareTo method for my class. Ideally, the class will be used in collections, and has to be sorted by an int value. I've found a messy way to do this by converting the int values into strings, then comparing those, but I would like to know if there is a better way to do this.

    You could subtract, unless you are worried about over/underflow.
    Then you can just compare the ints the old-fashioned way:
    import java.util.*;
    public class Test implements Comparable<Test> {
        int x;
        public int compareTo(Test that) {
            return this.x - that.x;
            //return this.x < that.x ? -1 : this.x > that.x ? 1 : 0;
    }

  • Problems accessing my compareTo method

    Could you any one help me on this please.
    I have 3 classes :
    1- "Test class" that creates the object (works fine) and redefines compareTo method
    2. "XListeChainee" that manage my linked list :
    - insert a new node (problems) in order
    3. "Test" which is the classe containing the main method. here is the code
    class Test {
    public static void test(){
    XListeChainee liste = new XListeChainee();
    liste.insererOrdonne(new TestClass("A"));
    liste.insererOrdonne(new TestClass("B"));
    liste.insererOrdonne(new TestClass("C"));
    liste.insererOrdonne(new TestClass("E"));
    liste.insererOrdonne(new TestClass("D"));
    // ------- here is the main method
    public static void main(String[] args){//main
    Test obj = new Test();/
    obj.test();
    }//end main
    here is the class TestClass with the compareTo method
    class TestClass implements Comparable{
    String data;
    TestClass(String data)
    this.data = data;
    }//end constructor
    public String toString(){
    return (data);
    public int compareTo(Object o) {
    TestClass n = (TestClass)o;
    int compData = data.compareTo(n.data);
    return compData ;
    }//end TestClass
    and this is my XListeChainee class (some of the code)
    public class XListeChainee
    private Noeud premierNoeud; //reference to first node
    private Noeud dernierNoeud; //reference to last node
    boolean estVide(){
    return premierNoeud == null;
    // ------ Insert an object: in order
    void insererOrdonne(Object element) {        
    // Creates a new node with the new element
    Noeud unNoeud;
    unNoeud = new Noeud();
    unNoeud.majElement(element) ;
    if ( premierNoeud == null ) { // if first node = null
    premierNoeud = unNoeud; // new node become first
    //------------------------- problem------------------------------
    //---- Compare the element in the first node with the element : Doesn't work
    // ---- System says that cannot resolve symbol - compareTo
    // This line says: if (firstNode.element.compareTo(element)>=0)
    else if ( premierNoeud.obtenirElement().compareTo(element) >= 0 ) {
    // Le nouvel element est < que le 1er element, alors il est inser� a la tete
    unNoeud.majSuivant(premierNoeud);
    premierNoeud = unNoeud;
    else {
    // Chercher la position du nouvel element dans la liste
    Noeud parcourir; // un noeud pour parcourir la liste
    Noeud prec; //un noeud toujour avant celui qui parcours la liste
    parcourir = premierNoeud.obtenirSuivant();
    prec = premierNoeud;
    while (parcourir != null && parcourir.obtenirElement().compareTo(element) < 0) {
    previous = parcourir;
    parcours = parcourir.obtenirSuivant();
    unNoeud.majSuivant(parcourir); // Insert newNode after previous.
    prec.majSuivant(unNoeud);
    Could you help me doing this please? I' sorry about some variable and method's names but I'm writing a program in french

    [snip]
    public int compareTo(Object o) {
    TestClass n = (TestClass)o;
    int compData = data.compareTo(n.data);
    return compData ;
    }//end TestClass[snip]
    : if (firstNode.element.compareTo(element)>=0)
    else if (
    e if (
    premierNoeud.obtenirElement().compareTo(element) >=0
    ) {What's up with the >=0 business in your method call?
    Based on what your method expects (an Object) I
    I don't know what you're trying to accomplish there?
    Also, please use code tags.Nevermind, after staring at it I can see the closing paranthesis now.

  • What's the difference between equals() and compareTo() method

    I'm confused between the two method from String class ,,, what's the main difference between equals() and compareTo() method?

    API docs give quite clear information IMHO
    public boolean equals(Object anObject)
    Compares this string to the specified object. The result is true if and only if the argument is not null and is
    a String object that represents the same sequence of characters as this object.
    public int compareTo(String anotherString)
    Compares two strings lexicographically. ....
    The result is a negative integer if this String object lexicographically precedes the argument string. The
    result is a positive integer if this String object lexicographically follows the argument string. The result is
    zero if the strings are equal; compareTo returns 0 exactly when the equals(Object) method would return
    true. Mike

  • Java CompareTo Method

    does anyone know how the string compareTo method actually works? I am trying to use a binary search to find a word in an arraylist with a specific prefix.
    i know that the compareTo method returns a 1 0 or -1 based on what the result of the comparison is but im interested in teh actual way that the comparison takes place.
    Since i will be comparing a prefix to a complete word, i would like to know if this would cause any problems due to the difference in string lengths.
    Do you guys have any other idea on how i can use a very fast searching method to search a sorted arraylist of words to see if any word with a specific prefix exists?

    i did that but i would still have to use compareTo because if the middle element does not have the prefix i am looking for then i would have to know if its on the right half or the left half of the Arraylist by comparing. right?
         public static int bSearch(ArrayList list, String pref)
              int result = -1;
              int low = 0;
              int high = list.size()-1;
              String s="";
              while(low <= high || result==-1)
                   int mid = (low + high)/2;
                   s = (String)list.get(mid);
                   if(s.startsWith(pref)==true)
                        result = mid;
                   else if(pref.compareTo(list.get(mid))<0)
                        high = mid - 1;
                   else
                        low = mid + 1;
              return result;
         }this is what i got so far but i am not sure if using compareTo method the way i am using it will work or not.

  • Calling a method from another file

    This is pretty basic stuff but i can't seem to get it right. I am calling a method from another file. The other file IS located in the same folder BUT when i compile i get errors
    "cannot find symbol" <===referring to limit and sieve i believe.
    The method name is "sieve" the file name is "PrimeSieve2008" and "limit" is the variable in brackets in the real method.
         public static void main (String [] args) {
    final int [] PRIMES;
    int sieve = PrimeSieve2008.sieve(limit);
         PRIMES = sieve(getValidInt());
              for (int j = 0; j<PRIMES.length; j++) {
                   System.out.println("Prime[" + j + "] = " + PRIMES[j]);
    Is "int sieve = PrimeSieve2008.sieve(limit)" the wrong way to call a file?
    Thanks a million,
    Alex
    Edited by: Simplistic2099 on Apr 3, 2008 7:47 PM
    Edited by: Simplistic2099 on Apr 3, 2008 7:49 PM

    Simplistic2099 wrote:
    the other method runs fine:
    "public static int[] sieve(final int limit){
    int candidate; // possible prime
    int count; // no. of primes found
    boolean[] mayBePrime = new boolean[limit+1];
    // remaining possibilities
    final int[] PRIMES; // array to return
    // initialize mayBePrime
    for ( int j = 0 ; j <= limit ; j++ ) {
    mayBePrime[j] = true;
    mayBePrime[0] = mayBePrime[1] = false;
    // apply sieve, and count primes
    candidate = 2;
    count = 0;
    while ( candidate <= limit ) {
    if ( mayBePrime[candidate] ) {
    count++;
    for ( int j = 2 * candidate ; j <= limit ; j += candidate ) {
    mayBePrime[j] = false;
    } // end for
    } // end if
    candidate++;
    } // end while
    // fill up new array with the primes found
    PRIMES = new int[count];
    count = 0;
    for (int j = 2 ; j <= limit ; j++ ) {
    if ( mayBePrime[j] ) {
    PRIMES[count] = j;
    count++;
    } // end if
    } // for
    return PRIMES;
    } // sieve
    I really am clueless here.in this one you are passing in limit.
    in the other one you are getting limit from somewhere outside of main.

  • Can we compare file contents of two files in the Application server?

    Hi,
    A file is generated daily to the application server. and i need to compare the generated file to the file generated on the previous day and prepare a report.
    Can we compare file contents of two generated files present in the Application server?
    If there is any alternative, please suggest.
    regards
    cs

    yes we can compare if the app server is Unix.
    cmp compare two binary files and report if different
    cmp is silent if the files are the
         same;
    if they differ, the byte and line number at which the first
    difference occurred is reported.
    REPORT ZUNIX line-size 400
                    no standard page heading.
    data: unixcom like   rlgrap-filename.  
    unixcom = 'cmp file1 file2'.
    data: begin of tabl occurs 500,
            line(400),
          end of tabl.
    data: lines type i.
    start-of-selection.
      refresh tabl.
      call 'SYSTEM' id 'COMMAND' field unixcom
                    id 'TAB'     field tabl[].
    "if the files are different then you will some content in tabl
    Regards
    Viajy  Babu Dudla

  • Is there a Compare Files extension or utility ?

    I am wanting to compare files within Edge Code. Is there a utility or extension available for this?

    Have a look here

  • Problemes with the method listFiles() in File class. I'm using JDeveloper 3.0

    Hi!
    Why can't I compile this snip of code?
    I get:
    Error: (19) method listFiles() not found in class java.io.File.
    Here is the code:
    package stream;
    import java.io.*;
    import java.util.*;
    public class myStream {
    public static void main(String[] args) {
    File myFile = new File("D:/myjava");
    File[] str = myFile.listFiles();
    Thanks in advance
    Henning

    There is no method "listFiles()" in "File" class. (JDK 1.1.8)
    You can try to use " list() " method which
    Returns a list of the files in the directory specified by this File object.
    raghu
    null

  • Calling method from jsp file

    Hi
    is it possible to call any method with in the class except handle method from jsp file?

    You can call , but it would not be a good design approach.A droplet can do the same task for you.
    otherwise :
    eg :
    <%@ page import="com.mypackage.MyClass"%>
    for Static access :
    <%
    String test= MyClass.myMethod();
    %>
    for normal classes :
    <%
    MyClass object = new MyClass();
    String test= object .myMethod();
    %>
    http://stackoverflow.com/questions/10918526/call-java-method-in-jsp-file
    http://www.javaworld.com/javaworld/jw-05-2003/jw-0523-calltag.html?page=2
    ```
    Praveer
    Edited by: Praveer Rai on Mar 26, 2013 5:08 PM

  • Doubt in compareTo method while sorting string having special character

    I used compareTo method of String to sort below strings
    ??che
    ??in
    p?ch?
    I got the output in the below order :
    p?ch?
    ??che
    ??in
    Why does ??che appear before ??in because from http://www.asciitable.com/ ascii value of *?* is *154*
    and that of *?* is *130* so shouldn't ??in appear ??che?
    Regards,
    Joshua

    jaay wrote:
    I used compareTo method of String to sort below strings
    ??che
    ??in
    p?ch?
    I got the output in the below order :
    p?ch?
    ??che
    ??in
    Why does ??che appear before ??in because from http://www.asciitable.com/ ascii value of *?* is *154*
    and that of *?* is *130* so shouldn't ??in appear ??che?
    Regards,
    JoshuaAre you sure your strings are using ASCII encoding, and not unicode? If it's the latter, the ASCII table won't matter at all and you'd need to check the values in a unicode table.

  • Can't compare files in VS 2012

    Hello,
    Randomly i can't compare files anymore in VS 2012 and only a restart of VS helps.
    The error message is:
    Microsoft Visual Studio
    One or both of these files are not text files and cannot be opened in the comparison window.
    C:\Users\wfuerst\AppData\Local\Temp\TFSTemp\vctmp23076_218344.sln
    C:\t\E\src\EFA_Integration\Solution\DefaultCustomer\DefaultCustomerSolution.sln
    The contents of the two files are different.
    OK  
    Whats wrong here and how can i fix this?
    Thanks,
    Wolfgang

    Same issue here. Can't find a pattern to reproduce but it occurs and only a VS2012 restart will let you compare any file again.
    I have VS2012 running against a TFS2012, TFS 2010 power tools installed.
    3. Can you open the files in notepad?
    YES, both
    4. Do you compare a local file and a server file?
    YES, Source path is filled out with the server location, Target path with the local
    5. Check the file in temp folder when you get this error.
    Checked, I can use winmerge effectively between the same 2 files VS is complaining about
    6. Is there any detail event log relate to this issue?
    No, couldn't find anything on the event logs

Maybe you are looking for

  • Installation problem with oracle 11i e-business suite

    Hai iam installing 11 i financials for the first time on windows server -2003 i have completed the first stages of validation system configuration . and later while extracting files from the location it shows error as 1.APPS_ORACLE_HOME environmental

  • Queries regarding creating Web Services in Oracle EBS 11i[Workaround found]

    Hi, We have an E-Business Suite 11i installation(11.5.10.2). In our implementation we are using some of the public APIs to insert & update data in EBS tables. Earlier this was done by calling the required PL/SQL procedures through dblinks. Now, we ne

  • Product  Costing Cycle

    Hi Can somebody explain me the entire cycle of PRODUCT COSTING configuration... 10 points will be rewarded.. Rgds

  • FIREPOD/ SPIDIF OUT NOT WORKING PLZ HELP

    HI So I've been liking the firepod by presonus on my macbook black 2.12 ghz, ran all the upgrades, love it for live gigs, thing is, i tried to connected it to my digidesign 888 via spidif out to 888 in and nothing comes out. i tried again on my DAT m

  • More Details about Multithreading Mode in User Management

    Good morning, we are working with Portal 7.0 on SP 14 and there is an option to activate the multithreading mode in the User Management part of the support desk. Since this option seems to significant speed up our login time i´am interested in more d