gpt4 book ai didi

java - 需要一种方法来读取两个文件并使用扫描器类输出差异

转载 作者:行者123 更新时间:2023-12-02 11:37:16 25 4
gpt4 key购买 nike

这就是我到目前为止所拥有的。我不知道从这里该去哪里。我需要一种方法来输出两个文件中的差异

    package JwolfrumCh6;
import java.util.*;
import java.io.*;
import java.util.Scanner;

public class JwolfrumCh6 {

public static void main(String[] args) throws FileNotFoundException
{
Scanner console = new Scanner(System.in);

System.out.print("Enter File one Name");
String file1 = console.nextLine();
Scanner input1 = new Scanner(new File(file1));

System.out.print("Enter File two Name");
String file2 = console.nextLine();
Scanner input2 = new Scanner(new File(file2));
}
public static void compareFiles(Scanner input1, Scanner input2) {

while(input1.hasNextLine() || input2.hasNextLine()) {

}

}
}

最佳答案

在 main 中调用静态方法并在compareFiles 方法中实现以下逻辑。

  1. 将文件 1 的所有行读取到 ArrayList
  2. 将文件 2 的所有行读取到另一个 ArrayList
  3. 使用 ArrayList 的 removeAll 方法(如下所示)来获取每个文件中的差异。

    import java.io.File;
    import java.io.FileNotFoundException;
    import java.util.ArrayList;
    import java.util.List;
    import java.util.Scanner;

    public class FML {

    public static void main(String[] args) throws FileNotFoundException {
    Scanner console = new Scanner(System.in);

    System.out.print("Enter File one Name");
    String file1 = console.nextLine();
    Scanner input1 = new Scanner(new File(file1));

    System.out.print("Enter File two Name");
    String file2 = console.nextLine();
    Scanner input2 = new Scanner(new File(file2));
    compareFiles(input1, input2);
    }

    public static void compareFiles(Scanner input1, Scanner input2) {
    List<String> list1 = new ArrayList<String>();
    List<String> list2 = new ArrayList<String>();
    while (input1.hasNextLine()) {
    list1.add(input1.nextLine());
    }
    while (input2.hasNext()) {
    list2.add(input2.nextLine());
    }
    List<String> tmpList = new ArrayList<String>(list1);
    tmpList.removeAll(list2);

    System.out.println("content from file1 which is different from file2");
    for(int i=0;i<tmpList.size();i++){
    System.out.println(tmpList.get(i));
    }

    System.out.println("content from file2 which is different from file2");

    tmpList = list2;
    tmpList.removeAll(list1);
    for(int i=0;i<tmpList.size();i++){
    System.out.println(tmpList.get(i));
    }

    }
    }

关于java - 需要一种方法来读取两个文件并使用扫描器类输出差异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48837316/

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