我有一个大学的任务,要求我从.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) {
}
}
答案 0 :(得分:2)
您不需要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
('银行')。