比较Java中的两个文件和打印差异

时间:2018-04-15 19:11:07

标签: java

我尝试比较两个文件并打印出它们之间的差异。但是,我的代码只打印最后一个句子,即每个文件中的第二个区别。

/*
-------------------------------
data1:
This file has a great deal of
text in it which needs to 

be processed.
-------------------------------
data2:
This file has a grate deal of 
text in it which needs to 

bee procesed.
-------------------------------
*/

import java.io.*;
import java.util.*;

public class CompareTwoFiles {
    public static void main(String[] args) throws FileNotFoundException {

        String first = "", second = "";
        String firstName = "", secondName = "";

        Scanner input = new Scanner(System.in);
        System.out.print("Enter a first file name: ");
        firstName = input.nextLine();
        System.out.print("Enter a second file name: ");
        secondName = input.nextLine();

        Scanner input1 = new Scanner(new File(firstName));//read first file
        while (input1.hasNextLine()) {
            first = input1.nextLine();
        }

        Scanner input2 = new Scanner(new File(secondName));//read second file
        while (input2.hasNextLine()) {
            second = input2.nextLine();
        }

        if (!first.equals(second)) {
            System.out.println("Differences found: " + "\n" + first + '\n' + second);
        }
    }
}

/*
output:
Enter a first file name: data1.txt
Enter a second file name: data2.txt
Differences found: 
be processed.
bee procesed.
*/

1 个答案:

答案 0 :(得分:4)

您的代码应为

Scanner input1 = new Scanner(new File(firstName));//read first file
Scanner input2 = new Scanner(new File(secondName));//read second file

while(input1.hasNextLine() && input2.hasNextLine()){
    first = input1.nextLine();   
    second = input2.nextLine(); 

    if(!first.equals(second)){
        System.out.println("Differences found: "+"\n"+first+'\n'+second);
    }
}

// optionally handle any remaining lines if the line count differs

以前你只比较过一次,最后一行。但是你需要在你阅读的每一行之后进行比较。