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 = reader1.read();
int i2 = reader2.read();
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 java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
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 = r1.read();
c2 = r2.read();
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
Output
Input 2
Output
