How to read a .csv file into an array list in java?

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;
}

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.

Leave a Comment