如何在Java中将.csv文件读取到数组列表中?
我有一个大学作业,要求我从.csv文件中获取数据并读取,处理和以三种不同的方法进行打印。这些说明要求我将数据读取到数组列表中,并编写了一些代码来执行此操作,但是我不确定是否正确完成了该操作。有人可以帮助我了解我应该如何将文件读入数组列表吗?
我的代码:
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 []数组列表,例如:
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;
}
同样,在您的情况下,最好在list
本地声明并从中返回它,method
而不是将元素添加到共享list
(“ bank”)中。
以上是 如何在Java中将.csv文件读取到数组列表中? 的全部内容, 来源链接: utcz.com/qa/426843.html