可以使用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文本文檔中不相同的字。