如何将.csv文件读入java中的数组列表? [英] How to read a .csv file into an array list in java?
问题描述
我有一个大学的任务,要求我从.csv文件中获取数据并读取,处理它,然后用三种不同的方法打印它。说明要求我将数据读入数组列表,我已经编写了一些代码,但我不确定我是否已正确完成。有人可以帮我理解我应该如何将文件读入数组列表吗?
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?
我的代码:
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) {
}
}
推荐答案
您不需要 2D
数组来存储文件内容, String []数组列表可以做,例如:
You don't need 2D
array to store the file content, a list of String[] arrays would do, e.g:
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;
}
此外,最好宣布列表
在本地并从方法
返回它,而不是将元素添加到共享的列表中
('bank ')在你的情况下。
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.
这篇关于如何将.csv文件读入java中的数组列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!