溫馨提示×

  • 首頁 > 
  • 問答 > 
  • 編程語言  > 
  • java中進(jìn)行兩個txt文本文檔的數(shù)據(jù)對比,找不不相同的字

java中進(jìn)行兩個txt文本文檔的數(shù)據(jù)對比,找不不相同的字

小億
147
2023-12-19 16:22:09
欄目: 編程語言

可以使用Java的IO流和字符串處理來實現(xiàn)兩個txt文本文檔的數(shù)據(jù)對比,找出不相同的字。

以下是一個簡單的示例代碼:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashSet;
import java.util.Set;

public class TextComparator {
    public static void main(String[] args) {
        String file1Path = "text1.txt";
        String file2Path = "text2.txt";

        try {
            Set<Character> diffChars = compareTextFiles(file1Path, file2Path);
            System.out.println("不相同的字:");
            for (Character ch : diffChars) {
                System.out.print(ch);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static Set<Character> compareTextFiles(String file1Path, String file2Path) throws IOException {
        Set<Character> diffChars = new HashSet<>();

        BufferedReader reader1 = new BufferedReader(new FileReader(file1Path));
        BufferedReader reader2 = new BufferedReader(new FileReader(file2Path));

        String line1, line2;
        while ((line1 = reader1.readLine()) != null && (line2 = reader2.readLine()) != null) {
            for (int i = 0; i < line1.length(); i++) {
                if (line1.charAt(i) != line2.charAt(i)) {
                    diffChars.add(line1.charAt(i));
                }
            }
        }

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

        return diffChars;
    }
}

上述代碼中,首先定義了兩個txt文本文檔的路徑 file1Pathfile2Path ,然后調(diào)用 compareTextFiles 方法進(jìn)行對比,返回不相同的字的字符集合 diffChars ,最后打印出不相同的字。

請注意,上述代碼僅比較了兩個文本文檔中對應(yīng)位置的字符是否相同,如果兩個文檔的字符數(shù)不一致,可能會導(dǎo)致數(shù)組越界異常。如果需要進(jìn)行更復(fù)雜的對比邏輯,可以根據(jù)具體需求進(jìn)行修改。

0