我想读取文本文件的内容,在分隔符上拆分,然后将每个部分存储在单独的数组中。
例如,-file-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 :(得分:1)
您可以为第一部分创建两个列表,为第二部分创建第二个列表:
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]