简体   繁体   English

Java同时读取两个文本文件

[英]Java read two text file at the same time

I'm new to Java Programming. 我是Java编程的新手。 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. cmp2.txt行多于cmp1.txt行。 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 : cmp1包含:

test1,1
test2,2

cmp2 contains : cmp2包含:

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) Test.main(Test.java:30)处的线程“ main”中的异常java.lang.NullPointerException

expected output : 预期产量:

test1   test11
test2   test14
        test15
        test9

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. 发生这种情况的原因是,您读取第一个文件的次数与第二个文件中的行的读取次数相同,但是您对检查第二个文件的结果进行null 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. 在调用split()之前,请不要对它进行null -check line1 ,这将导致第二个文件比第一个文件包含更多行时引发NullPointerException

You can fix this problem by adding a null check on line1 , and replacing it with an empty String when it's null . 您可以通过添加一个解决这个问题, null的检查line1 ,并用空替换它String时,它的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
}

I would suggest 我会建议

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

That would read line by line in each file until either one of the files reaches EOF. 这将逐行读取每个文件,直到其中一个文件到达EOF。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM