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

比较两个文件并打印Java中的差异,java,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 wh

我试着比较两个文件并打印出它们之间的差异。但是,我的代码只打印最后一句话,这是每个文件中的第二个差异所在

/*
-------------------------------
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.
*/
你的代码应该是

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
以前你只比较过一次,最后一行。但您需要在阅读每一行之后进行比较。

您的代码应该是

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

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

好吧,你只比较最后一句话。在
while
循环中,变量
第一个
第二个
总是被覆盖。最后两个变量都存储了两个文件的最后一行。好吧,你只比较最后一句话。在
while
循环中,变量
first
second
总是被覆盖。最后两个变量都存储了两个文件的最后一行。