jeudi 26 avril 2018

Compare 2 text files in java and write the difference in both separately into another file

This is the code I have written to perform a validation mechanism for comparing 2 files. I want to know is there a way to write it in a more performing way, because both of my files can have millions of records in it and this I believe will be slow in those cases.

I don't do a line by line comparison because order of the lines may be different in both files.

public static void main(String[] args) throws Exception {
BufferedReader br1 = null;
BufferedReader br2 = null;
BufferedWriter br3 = null;
String sCurrentLine;
int linelength;
List<String> list1 = new ArrayList<String>();
List<String> list2 = new ArrayList<String>();
List<String> unexpectedrecords = new ArrayList<String>();

br1 = new BufferedReader(new FileReader("expected.txt"));

br2 = new BufferedReader(new FileReader("actual.txt"));

while ((sCurrentLine = br1.readLine()) != null) {
    list1.add(sCurrentLine);
}
while ((sCurrentLine = br2.readLine()) != null) {
    list2.add(sCurrentLine);
}
List<String> expectedrecords = new ArrayList<String>(list1);

List<String> actualrecords = new ArrayList<String>(list2);

if (expectedrecords.size() > actualrecords.size()) {
    linelength = expectedrecords.size();
} else {
    linelength = actualrecords.size();
}

for (int i = 0; i < linelength; i++) {
    if (actualrecords.contains(expectedrecords.get(i))) {
        actualrecords.remove(expectedrecords.get(i));
    } else {
        unexpectedrecords.add(actualrecords.get(i));
    }
}

br3 = new BufferedWriter(new FileWriter(new File("c.txt")));
br3.write("Records which are not present in actual");
for (int x = 0; x < unexpectedrecords.size(); x++) {
    br3.write(unexpectedrecords.get(x));
    br3.newLine();
}
br3.write("Records which are in actual but no present in expected");
for (int i = 0; i < actualrecords.size(); i++) {
    br3.write(actualrecords.get(i));
    br3.newLine();
}
br3.flush();
br3.close();

}

Aucun commentaire:

Enregistrer un commentaire