Issue
I've written code for comparing two text files. It is showing the result only if the match is in same position as in the first text file. I wanted to find match anywhere in other text file. Please suggest a way to do this. The code which i've written is shown below :
import java.io.*;
public class CompareTextFiles {
public static void main(String args[]) throws Exception {
FileInputStream fstream1 = new FileInputStream("text1.txt");
FileInputStream fstream2 = new FileInputStream("text2.txt");
DataInputStream in1= new DataInputStream(fstream1);
DataInputStream in2= new DataInputStream(fstream2);
BufferedReader br1 = new BufferedReader(new InputStreamReader(in1));
BufferedReader br2 = new BufferedReader(new InputStreamReader(in2));
String strLine1, strLine2;
while((strLine1 = br1.readLine()) != null && (strLine2 = br2.readLine()) != null){
if(strLine1.equals(strLine2)){
System.out.println(strLine1);
}
}
}
}
Solution
Store the whole content of one of the files to a string, rather than comparing line by line.
String strLine1, strLine2;
StringBuffer strFile2 = new StringBuffer();
//Store the contents of File2 in strFile2
while((strLine2 = br2.readLine()) != null) {
strFile2.append(strLine2);
}
//Check whether each line of File1 is in File2
while((strLine1 = br1.readLine()) != null){
if(strFile2.toString().contains(strLine1)){
System.out.println(strLine1);
}
}
Answered By - Raghavendra