溫馨提示×

java中進行兩個txt文本文檔的數據對比找不相同的字

小億
242
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
亚洲午夜精品一区二区_中文无码日韩欧免_久久香蕉精品视频_欧美主播一区二区三区美女