[英]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.