【问题标题】:Java read two text file at the same timeJava同时读取两个文本文件
【发布时间】:2015-04-08 02:48:28
【问题描述】:

我是 Java 编程新手。这个真的太长了,看不懂,但我只是想知道是否有可能像这样读取两个文本文件? cmp2.txt 行多于 cmp1.txt 行。提前致谢!

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 包含:

test1,1
test2,2

cmp2 包含:

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

脚本输出:

test1   test11
test2   test14

Test.main(Test.java:30) 处的线程“main”java.lang.NullPointerException 中的异常

预期输出:

test1   test11
test2   test14
        test15
        test9

【问题讨论】:

    标签: java io bufferedreader


    【解决方案1】:

    发生这种情况是因为您读取第一个文件的次数与第二个文件中的行数一样多,但是您null-检查了读取第二个文件的结果。在调用split() 之前,您没有null-check line1,这会在第二个文件的行数多于第一个文件时导致NullPointerException

    您可以通过在line1 上添加null 检查并在null 时将其替换为空的String 来解决此问题。

    这将读取两个文件以完成,无论哪个更长:

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

    【讨论】:

    • 变量 line1 可能尚未初始化
    • @tuturyokgaming 那是因为你没有在声明中添加= null。应该是String line2=null,而不仅仅是String line2
    • 所以这意味着我的预期输出是不可能的?
    • @tuturyokgaming 为什么,当然有可能。你是不是改了声明重新编译了?
    • 是的,我更改了声明并重新编译它,但输出不同。
    【解决方案2】:

    建议

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

    这将在每个文件中逐行读取,直到其中一个文件到达 EOF。

    【讨论】:

    • 这个是对的,但是直到到达EOF才打印出line2的数据
    猜你喜欢
    • 1970-01-01
    • 2012-07-02
    • 2018-06-06
    • 2014-05-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-03-05
    • 1970-01-01
    相关资源
    最近更新 更多