java代码比较test1.txt及test2.txt文件的内容
时间: 2023-08-05 21:04:48 浏览: 139
J2ME_test.rar_environmenttest.j_java 测试
以下是比较两个文件内容的Java代码:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class FileComparator {
public static void main(String[] args) throws IOException {
String file1 = "test1.txt";
String file2 = "test2.txt";
BufferedReader reader1 = new BufferedReader(new FileReader(file1));
BufferedReader reader2 = new BufferedReader(new FileReader(file2));
String line1 = reader1.readLine();
String line2 = reader2.readLine();
boolean areEqual = true;
int lineNum = 1;
while (line1 != null || line2 != null) {
if (!line1.equals(line2)) {
areEqual = false;
System.out.println("Content in file " + file1 + " is not equal to content in file " + file2 +
" at line " + lineNum);
System.out.println(file1 + ": " + line1);
System.out.println(file2 + ": " + line2);
}
line1 = reader1.readLine();
line2 = reader2.readLine();
lineNum++;
}
reader1.close();
reader2.close();
if (areEqual) {
System.out.println("Content of both files is equal.");
}
}
}
```
这个程序会读取两个文件的内容,并逐行进行比较。如果发现两个文件的某一行不相同,程序会输出该行在文件中的行号以及该行的内容。如果两个文件完全相同,则程序会输出一条消息表明它们的内容是相等的。
阅读全文