How to compare two text files content in Java


We need to write a program to compare two text files and return a boolean value. If both the text files have exactly same content, then our method should return true, otherwise it should return false. We pass Path of both files as method parameter.

prototype of our method:
boolean compareTextFiles ( String,String ) ;

To compare two text files, both the files should be first loaded in the bufferedReader.

BufferedReader reader1 = new BufferedReader(new FileReader(Path1)); BufferedReader reader2 = new BufferedReader(new FileReader(Path2));
We declare two integer variables i1 and i2 which read the buffer one value at the time until we reach end of any one of the given two files. If end of file is reached, read() function will return -1.
int i1 =; int i2 =;
If any one of the file finished before the another, length of two files is unequal, so return false. OR If two ASCII values in i1 and i2 are not equal, return false.
if(i1 == -1 && i2 == -1){ return true; } else if(i1 == -1 || i2 == -1 || i1!=i2){ return false; }
Here's the full program:
import; import; import; import; public class Example{ static boolean compareTextFiles ( String file1, String file2) throws FileNotFoundException, IOException{ BufferedReader r1 = new BufferedReader(new FileReader(file1)); BufferedReader r2 = new BufferedReader(new FileReader(file2)); int c1=0, c2=0; while(true){ c1 =; c2 =; if(c1==-1 && c2==-1) return true; else if(c1==-1 || c2==-1 || c1!=c2){ return false; } } } public static void main(String[] args) throws IOException{ String file1 = "Path to file1"; String file2 = "Path to file2"; if(compareTextFiles(file1, file2)){ System.out.println("Files are same"); } else{ System.out.println("Files are different"); } } }

Input 1

compare two text files content in Java Input


compare 2 txt files data in Java Output

Input 2

compare 2 txt files data in Java Input


compare two text files content in Java Output

Need Programming or any Technical Related Books, Courses or Help Chat with us

Myntra [CPS] IN


Sponsored Advertisement

Udemy WW

Norton [CPS] WW

Online Games
Play 2048 Game Online and Relax.
Play 2048 Game Online

Search Tags