温馨提示×

java中进行两个txt文本文档的数据对比找不相同的字

小亿
91
2023-12-20 16:56:40
栏目: 编程语言

可以使用Java中的文件读取和字符串比较方法来实现两个txt文本文档的数据对比,找出其中不相同的字。

首先,需要使用Java中的File类和BufferedReader类来读取两个txt文本文档的内容。具体代码如下:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;

public class TextComparison {
    public static void main(String[] args) {
        String file1Path = "path_to_file1.txt"; // 第一个txt文档的路径
        String file2Path = "path_to_file2.txt"; // 第二个txt文档的路径

        try {
            File file1 = new File(file1Path);
            File file2 = new File(file2Path);

            BufferedReader reader1 = new BufferedReader(new FileReader(file1));
            BufferedReader reader2 = new BufferedReader(new FileReader(file2));

            String line1, line2;
            int lineNum = 1;

            while ((line1 = reader1.readLine()) != null && (line2 = reader2.readLine()) != null) {
                for (int i = 0; i < line1.length(); i++) {
                    if (i >= line2.length() || line1.charAt(i) != line2.charAt(i)) {
                        System.out.println("File1 line " + lineNum + ", position " + (i + 1) + ": " + line1.charAt(i));
                    }
                }
                lineNum++;
            }

            // 判断两个文件是否有剩余的不同字符
            while ((line1 = reader1.readLine()) != null) {
                for (int i = 0; i < line1.length(); i++) {
                    System.out.println("File1 line " + lineNum + ", position " + (i + 1) + ": " + line1.charAt(i));
                }
                lineNum++;
            }

            while ((line2 = reader2.readLine()) != null) {
                for (int i = 0; i < line2.length(); i++) {
                    System.out.println("File2 line " + lineNum + ", position " + (i + 1) + ": " + line2.charAt(i));
                }
                lineNum++;
            }

            reader1.close();
            reader2.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

在上述代码中,需要将"path_to_file1.txt"和"path_to_file2.txt"替换为实际的txt文档路径。

代码的实现逻辑是逐行读取两个txt文档的内容,然后逐个字符比较。如果发现字符不相同,则将其输出。最后,如果两个文件的行数不一致,需要将有剩余字符的那个文件的字符也输出。

通过上述代码,即可找到两个txt文本文档中不相同的字。

0