2017-07-18 159 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

相关问题