gpt4 book ai didi

java - 将每行逗号分隔的文件拆分为数组

转载 作者:行者123 更新时间:2023-12-01 07:04:03 25 4
gpt4 key购买 nike

目标:我正在尝试将 .txt 文件处理为 String[]。文件必须按行读取,拼接在“,”上并存储在数组中。每个元素(每行 6 个元素)必须在数组中拥有自己的索引,并且必须可以单独访问。

文件(部分):

210,20140101,    1,   60,   67,   -1
210,20140101, 2, 60, 65, 0
210,20140101, 3, 60, 58, 0
210,20140101, 4, 60, 56, 0
210,20140101, 5, 60, 49, 0
210,20140101, 6, 60, 53, 0
210,20140101, 7, 60, 55, 0
210,20140101, 8, 70, 59, 0

到目前为止的代码:

try (BufferedReader br = new BufferedReader(new FileReader(path))) {
for (String line; (line = br.readLine()) != null;) {
counter++;
if (counter > 51) {
line = br.readLine();
line = line.trim();
list = Arrays.asList(line.split("\\s*,\\s*"));
}
}
}

for (String x : list) {
System.out.println(x);
}

到目前为止的输出:

391
20141231
24
20
1
0

这正是我所需要的,但是对于每一行(存储在字符串数组中)。使用上面的代码仅将文件的最后一行存储在数组中。

我已经尝试过建议 herehere 。有什么建议或提示吗?

最佳答案

list = Arrays.asList(line.split("\\s*,\\s*"));

此行只是替换现有元素,因此您需要追加元素,切勿使用 = 将元素添加到 list 变量。

这可能会有所帮助:

list.addAll(Arrays.asList(line.split("\\s*,\\s*")));

关于java - 将每行逗号分隔的文件拆分为数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31156551/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com