9

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?

my code:

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) {

    }
}
4
  • Is there a fixed schema for the file that you are reading? Commented Feb 11, 2017 at 0:36
  • @Kot the file is 600 or so lines with 12 comma separated parts each Commented Feb 11, 2017 at 0:42
  • You should note an Array of strings and an ArrayList are not the same thing. If the instructions require an ArrayList then you should look into that class. Commented Feb 11, 2017 at 0:44
  • Do you need to be able to handle quotation marks correctly? These can be used around a field in CSV, and they need to be used if a field contains a comma. Commented Feb 11, 2017 at 1:02

1 Answer 1

11

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.

Sign up to request clarification or add additional context in comments.

1 Comment

Nice, but cooler having the separator as a parameter as for CSV, its not always comma.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.