Converting CSV File Into 2D Array

前端 未结 5 1661
南笙
南笙 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:32

    This is my implemented code:

    String fileName = "myfile.csv";
    List> list = new ArrayList>();
    BufferedReader br = new BufferedReader(new FileReader(fileName));
    String line = br.readLine();
    String[] headers = line.split(";");
    for(String header: headers) {
        List subList = new ArrayList();
        subList.add(header);
        list.add(subList);
    }
    while((line = br.readLine()) != null) {
        String[] elems = line.split(";");
        for(int i = 0; i < elems.length; i++) {
            list.get(i).add(elems[i]);
        }
    }
    br.close();
    int rows = list.size();
    int cols = list.get(0).size();
    String[][] array2D = new String[rows][cols];
    for(int row = 0; row < rows; row++) {
        for(int col = 0; col < cols; col++) {
            array2D[row][col] = list.get(row).get(col);
        }
    }
    

    The array2D is your wants.

提交回复
热议问题