gpt4 book ai didi

java - 比较两个文件并在 Java 中打印差异

转载 作者:行者123 更新时间:2023-11-29 08:28:59 25 4
gpt4 key购买 nike

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

/*
-------------------------------
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

之前您只比较了一次,即最后一行。但是你需要在阅读每一行之后进行比较。

关于java - 比较两个文件并在 Java 中打印差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49845793/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com