只需要打印一次Unterschiede gefunden:
while(sc.hasNextLine() || sc1.hasNextLine()) {
i++;
try {
text1 = sc.nextLine();``
text2 = sc1.nextLine();
if(!text1.equals(text2)){
System.out.println("Unterschiede gefunden:");
System.out.printf("Zeile %d :\n",i);
System.out.println(text1);
System.out.println(text2);
}
}catch(NoSuchElementException nse) {
text2 = " ";
}
}
答案 0 :(得分:0)
确定一个文本文件是否与另一个文本文件不同。一旦检测到一个文件行与另一文件行不同,请通知用户(正如您所做的那样),并从您的 IF 中的while循环中中断代码块以停止处理文件行,例如:
if(!text1.equals(text2)){
System.out.println("Unterschiede gefunden:"); // Difference Detected!
System.out.println("Zeile " + i + ":\n"); // At file line #.
System.out.println("File A: " + text1); // Text line in File A.
System.out.println("File B: " + text2); // Text line in File B.
break; // Break out of the WHILE loop.
}
您还考虑了以下事实,即文件A 可能比文件B 包含更多或更少的行,这很好,但是您应该在退出时退出 也在此时循环,因为您现在可以确定文件A 与文件B 不同,例如:
// These two variables are used to see which file
// contains more of fewer lines.
int fileACount = 0;
int fileBCount = 0;
// Read the two files...
while (sc.hasNextLine() || sc1.hasNextLine()) {
try {
String fileAText = sc.nextLine();
fileACount++;
String fileBText = sc1.nextLine();
fileBCount++;
if (!fileAText.equals(fileBText)) {
System.out.println("Unterschiede gefunden:");
System.out.printf("Zeile %d :\n", fileACount);
System.out.println(fileAText);
System.out.println(fileBText);
break;
}
}
catch (NoSuchElementException nse) {
// Using a Ternary Operator below so as to
// indicate which file contains more lines.
String fileWithMoreLines = fileACount > fileBCount ? "A" : "B";
System.out.println("Files are different! File " +
fileWithMoreLines + " contains MORE Lines.");
break;
}
}
别忘了关闭文件。