Java:读取2个文件并逐行比较

时间:2016-02-05 21:54:31

标签: java while-loop readfile writefile

我试图逐行比较两个文件。让我们举个例子:

File1中

a,b,c,d,12
e,f,g,h,20
h,g,t,y,30

文件2

f,g,h,j,30
e,h,j,f,50
a,b,c,d,60
e,f,g,h,70

我希望我的输出像:

a,b,c,d,12,50
e,f,g,h,20,70

我已经写了这段代码:

while ((line1 = bufferedFormattedReaderMaster.readLine()) != null) {

    temp1 = line1.substring(0, 7);
    temp3 = line1.substring(8, 10);

    while ((line2 = bufferedFormattedReaderAnalytical.readLine()) != null) {

        temp2 = line2.substring(0, 7);
        temp4 = line2.substring(8, 10);

        if (temp1.equals(temp2)) {

            System.out.println("OH YES");
            bufferedWriterFinalResults.write(temp1 + ","  +temp3 + "," + temp4);
            bufferedWriterFinalResults.newLine();
            numberOfFinalResults++;

        }   
    }
}

但我的输出只是:

a,b,c,d,12,50 

而不是下一行。

1 个答案:

答案 0 :(得分:0)

bufferedFormattedReaderMaster和bufferedFormattedReaderAnalytical只能读取一次。在I / O上提升你的技能。我做了一个简单的基于列表的代码转换。代码可能无法编译,但这大致是您必须实现的。还有更好的方法。

List<String> bufferedFormattedReaderMasterList =new ArrayList<String>();
List<String> bufferedFormattedReaderAnalyticalList =new ArrayList<String>();
    while ((line1 = bufferedFormattedReaderMaster.readLine()) != null) {

                   bufferedFormattedReaderMasterList.add(line1 );
                }


    while ((line2 = bufferedFormattedReaderAnalytical.readLine()) != null) {

                   bufferedFormattedReaderAnalyticalList.add(line2);
                }



for(String line1:bufferedFormattedReaderMasterList) {

                    temp1 = line1.substring(0, 7);
                    temp3 = line1.substring(8, 10);

                    for(String line2:bufferedFormattedReaderAnalyticalList) {

                        temp2 = line2.substring(0, 7);
                        temp4 = line2.substring(8, 10);

                        if (temp1.equals(temp2)) {

                            System.out.println("OH YES");
                            bufferedWriterFinalResults.write(temp1 + ","  +temp3 + "," + temp4);
                            bufferedWriterFinalResults.newLine();
                            numberOfFinalResults++;

                        }   
                    }
                }