user1739824
user1739824

Reputation: 21

I am trying a simple Compare 2 text files and print the diff between the 2

import java.io.*;

public class CheckingTwoFilesAndComparing implements Serializable {

private static final long serialVersionUID = 1L;

static String FILE_ONE = "/Users/abextra/myText1.txt";
static String FILE_TWO = "/Users/abextra/myText2.txt";

public static void main(String[] args) {

    try {
        CompareFile(FILE_ONE, FILE_TWO);

    } catch (Exception e) {
        e.printStackTrace();
    }
}


private static void CompareFile(String fILE_ONE2, String fILE_TWO2)
        throws Exception {

    File f1 = new File("FILE_ONE");
    File f2 = new File("FILE_TWO");

    FileReader fR1 = new FileReader(f1);
    FileReader fR2 = new FileReader(f2);

    BufferedReader reader1 = new BufferedReader(fR1);
    BufferedReader reader2 = new BufferedReader(fR2);

    String line1 = null;
    String line2 = null;

    while (((line1 = reader1.readLine()) != null)
            &&((line2 = reader2.readLine()) != null)) {
        if (!line1.equalsIgnoreCase(line2)) {
            System.out.println("The files are DIFFERENT");
        } else {
            System.out.println("The files are identical");
        }

    }
    reader1.close();
    reader2.close();

   }
}

Here are contents of the 2 Text files that exist in the path mentioned in the code above

==myText1.txt===
1,This is first line, file
2,This is second line, file
3,This is third line , file
4,This is fourth line, file

==myText2.txt===
1,This is first line, file
2,This is second line, file
3,This is third  line, file
4,This is fourth line, file
5,This is fifth line, file

I am a newbie to java . I used eclipse debugger and I see that I keep getting "FileNot found"exception - can someone please help? Thanks much!

Upvotes: 2

Views: 5024

Answers (3)

Bhavik Shah
Bhavik Shah

Reputation: 5183

Also The FileNotFoundException can be thrown when the file is open. (this happens only when you try to write to an already opened file)

Try closing the file and then running the program.

Upvotes: 1

Anthony Neace
Anthony Neace

Reputation: 26023

File f1 = new File("FILE_ONE");
File f2 = new File("FILE_TWO");

Try removing the quotes here. You declared FILE_ONE and FILE_TWO as variables earlier in your program, but you aren't calling them. Instead, you've directly called a string "FILE_ONE," which will of course not be found. So replace it with the parameters you passed to CompareFile...

File f1 = new File(fILE_ONE2);
File f2 = new File(fILE_TWO2);

And tell us if that takes care of it.

Upvotes: 4

Roflo
Roflo

Reputation: 255

You have to remove the quotes from:

File f1 = new File("FILE_ONE");

and

File f2 = new File("FILE_TWO");

Also, make sure in the files' path "/Users/abextra/myText1.txt", "Users" is really supposed to be uppercase. On many systems, /users/ is lowercase.

Upvotes: 1

Related Questions