如何将 .csv 文件读入 java 中的数组列表? [英] How to read a .csv file into an array list in java?

查看:25
本文介绍了如何将 .csv 文件读入 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;
}

此外,最好在本地声明 list 并从 method 返回它,而不是将元素添加到共享的 list ('银行')在你的情况下.

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆