Converting CSV File Into 2D Array

前端 未结 5 1660
南笙
南笙 2021-01-19 03:45

I have an example of my idea in a 1d array. It will only output the columns. My idea is to use a 2d array to select the row and column. Here my code:

String          


        
5条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-19 04:26

    I would use a dynamic structure to read all lines. Also you should use a try-resource block to close the streams automatically.

    public static String[][] readCSV(String path) throws FileNotFoundException, IOException {
        try (FileReader fr = new FileReader(path);
                BufferedReader br = new BufferedReader(fr)) {
            Collection lines = new ArrayList<>();
            for (String line = br.readLine(); line != null; line = br.readLine()) {
                lines.add(line.split(";"));
            }
            return lines.toArray(new String[lines.size()][]);
        }
    }
    

提交回复
热议问题