我是 Java 编程新手。这确实太长了,无法阅读,但我只是想知道是否有可能像这样读取两个文本文件? cmp2.txt 行多于 cmp1.txt 行。提前致谢!
String input1 = "C:\\test\\compare\\cmp1.txt";
String input2 = "C:\\test\\compare\\cmp2.txt";
BufferedReader br1 = new BufferedReader(new FileReader(input1));
BufferedReader br2 = new BufferedReader(new FileReader(input2));
String line1;
String line2;
String index1;
String index2;
while ((line2 = br2.readLine()) != null) {
line1 = br1.readLine();
index1 = line1.split(",")[0];
index2 = line2.split(",")[0];
System.out.println(index1 + "\t" + index2);
cmp1 包含:
test1,1
test2,2
cmp2 包含:
test11,11
test14,14
test15,15
test9,9
脚本输出:
test1 test11
test2 test14
Exception in thread "main" java.lang.NullPointerException at Test.main(Test.java:30)
预期输出:
test1 test11
test2 test14
test15
test9
最佳答案
发生这种情况是因为您读取第一个文件的次数与第二个文件中的行数相同,但您null
检查读取第二个文件的结果。在调用 split()
之前,不要对 line1
进行 null
检查,这会在第二个文件的行数多于第一个文件时导致 NullPointerException
。
您可以通过在 line1
上添加 null
检查来解决此问题,并在其为 null
时将其替换为空的 String
。
这将完整读取两个文件,无论哪个文件较长:
while ((line2 = br2.readLine()) != null || (line1 = br1.readLine()) != null) {
if (line1 == null) line1 = "";
if (line2 == null) line2 = "";
... // Continue with the rest of the loop
}
关于Java同时读取两个文本文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29505044/