Search code examples
javaiobufferedreader

Java read two text file at the same time


I'm new to Java Programming. This one is really too long to read, but I'm just wondering if it's possible that reading two text file like this? cmp2.txt line is more than cmp1.txt line. Thanks in advance!

String input1 = "C:\\test\\compare\\cmp1.txt";
String input2 = "C:\\test\\compare\\cmp2.txt";

BufferedReader br1 = new BufferedReader(new FileReader(input1));

BufferedReader br2 = new BufferedReader(new FileReader(input2)); 

String line1;
String line2;

String index1;
String index2;

while ((line2 = br2.readLine()) != null) {
    line1 = br1.readLine();

    index1 = line1.split(",")[0];
    index2 = line2.split(",")[0];
    System.out.println(index1 + "\t" + index2);

cmp1 contains :

test1,1
test2,2

cmp2 contains :

test11,11
test14,14
test15,15
test9,9

script output :

test1   test11
test2   test14

Exception in thread "main" java.lang.NullPointerException at Test.main(Test.java:30)

expected output :

test1   test11
test2   test14
        test15
        test9

Solution

  • This happens because you are reading the first file as many times as there are lines in the second file, but you null-check on the result of reading the second file. You do not null-check line1 before calling split() on it, which causes a NullPointerException when the second file has more lines than the first one.

    You can fix this problem by adding a null check on line1, and replacing it with an empty String when it's null.

    This would read both files to completion, no matter which one is longer:

    while ((line2 = br2.readLine()) != null || (line1 = br1.readLine()) != null) {
        if (line1 == null) line1 = "";
        if (line2 == null) line2 = "";
        ... // Continue with the rest of the loop
    }