[英]Java read two text file at the same time
我是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
Test.main(Test.java:30)处的线程“ main”中的异常java.lang.NullPointerException
预期产量:
test1 test11
test2 test14
test15
test9
发生这种情况的原因是,您读取第一个文件的次数与第二个文件中的行的读取次数相同,但是您对检查第二个文件的结果进行null
。 在调用split()
之前,请不要对它进行null
-check line1
,这将导致第二个文件比第一个文件包含更多行时引发NullPointerException
。
您可以通过添加一个解决这个问题, null
的检查line1
,并用空替换它String
时,它的null
。
无论哪个更长,这都会读取两个文件:
while ((line2 = br2.readLine()) != null || (line1 = br1.readLine()) != null) {
if (line1 == null) line1 = "";
if (line2 == null) line2 = "";
... // Continue with the rest of the loop
}
我会建议
while ((line2 = br2.readLine()) != null &&
(line1 = br1.readLine()) != null) {
这将逐行读取每个文件,直到其中一个文件到达EOF。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.