2017-07-18 162 views
0

我想讀取文本文件的內容,在分隔符上分割,然後將每個部分存儲在單獨的數組中。Java - 讀取並存儲在數組中

例如,文件-name.txt包含了所有在新行不同的字符串:

football/ronaldo 
f1/lewis 
wwe/cena 

所以我想讀的文本文件的內容,分裂的分隔符「/」和店在一個數組中的分隔符之前的字符串的第一部分,以及在另一個數組中的分隔符之後的第二部分。這就是我試圖到目前爲止做:

try { 

    File f = new File("the-file-name.txt"); 

    BufferedReader b = new BufferedReader(new FileReader(f)); 

    String readLine = ""; 

    System.out.println("Reading file using Buffered Reader"); 

    while ((readLine = b.readLine()) != null) { 
     String[] parts = readLine.split("/"); 

    } 

} catch (IOException e) { 
    e.printStackTrace(); 
} 

這是我迄今實現,但我不知道如何從這裏下去,在完成計劃的任何幫助將不勝感激。

+0

你一定要明白,你是分裂的'-'權現在... – litelite

+1

對於你的問題,我認爲像[[List]](https://docs.oracle.com/javase/7/docs/api/java/util/List.html)會更合適比一些陣列 – litelite

+0

「在一個單獨的陣列」,你的意思是一個全新的陣列fo r每個字? –

回答

1

您可以創建兩個列表之一的第一部分和SE秒第二部分:

List<String> part1 = new ArrayList<>();//create a list for the part 1 
List<String> part2 = new ArrayList<>();//create a list for the part 2 

while ((readLine = b.readLine()) != null) { 
    String[] parts = readLine.split("/");//you mean to split with '/' not with '-' 

    part1.add(parts[0]);//put the first part in ths list part1 
    part2.add(parts[1]);//put the second part in ths list part2 
} 

輸出

[football, f1, wwe] 
[ronaldo, lewis, cena] 
+0

感謝您的答覆,但是當我運行該程序時,我在線程「main」java.lang.ArrayIndexOutOfBoundsException中得到一個異常:1來自此行part2.add(parts [1 ]); – qwerty

+0

@qwerty這意味着你沒有一行不匹配'string1/string2'你能不能請分享你所有的文件? –

+0

謝謝我已經整理出來 – qwerty

相關問題