如何将 .csv 文件读入 java 中的数组列表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42170837/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to read a .csv file into an array list in java?
提问by abe
I have an assignment for college that requires I take data from a .csv file and read it, process it, and print it in three separate methods. The instructions require that I read the data into an array list I have written some code to do so but I'm just not sure if I've done it correctly. Could someone help me understand how exactly I am supposed to read the file into an array list?
我有一个大学作业,要求我从 .csv 文件中获取数据,并以三种不同的方法读取、处理和打印它。这些说明要求我将数据读入数组列表中,我为此编写了一些代码,但我不确定我是否正确完成了操作。有人能帮我理解我应该如何将文件读入数组列表吗?
my code:
我的代码:
public void readData() throws IOException {
int count = 0;
String file = "bank-Detail.txt";
try {
BufferedReader br = new BufferedReader(new FileReader(file));
String line = "";
while ((line = br.readLine()) != null) {
bank.add(line.split(","));
String[][] v = (String[][]) bank.toArray(new String[bank.size()][12]);
}
} catch (FileNotFoundException e) {
}
}
采纳答案by Darshan Mehta
You don't need 2D
array to store the file content, a list of String[] arrays would do, e.g:
你不需要2D
数组来存储文件内容,一个 String[] 数组列表就可以了,例如:
public List<String[]> readData() throws IOException {
int count = 0;
String file = "bank-Detail.txt";
List<String[]> content = new ArrayList<>();
try(BufferedReader br = new BufferedReader(new FileReader(file))) {
String line = "";
while ((line = br.readLine()) != null) {
content.add(line.split(","));
}
} catch (FileNotFoundException e) {
//Some error logging
}
return content;
}
Also, it's good practice to declare the list
locally and return it from the method
rather than adding elements into a shared list
('bank') in your case.
此外,在您的情况下,最好在list
本地声明并返回它,method
而不是将元素添加到共享list
(“银行”)中。