我试图比较两个文件并打印出它们之间的差异。但是,我的代码只打印最后一句,这是每个文件中第二个差异的位置。
/*
-------------------------------
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
以前您只比较一次,即最后一行。但是你需要在你阅读的每一行之后进行比较。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句