'Converting CSV File Into 2D Array

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 fName = "c:\\csv\\myfile.csv";
String thisLine; 
int count=0; 
FileInputStream fis = new FileInputStream(fName);
DataInputStream myInput = new DataInputStream(fis);
int i=0; 

while ((thisLine = myInput.readLine()) != null) {
     String strar[] = thisLine.split(";");
     out.println(strar[1]); // Here column 2
}

myfile.csv

Id;name
E1;Tim
A1;Tom

Output:

name Tim Tom



Solution 1:[1]

I would just add the split result (String[]) to a List then if you really want it as a 2d array then convert it after the fact.

List<String[]> lines = new ArrayList<String[]>();
while ((thisLine = myInput.readLine()) != null) {
     lines.add(thisLine.split(";"));
}

// convert our list to a String array.
String[][] array = new String[lines.size()][0];
lines.toArray(array);

Solution 2:[2]

First thing we don't know how many lines are there in the csv file. So it's impossible to determine the length of the 2d array. We have to increment the size of the array according to this case. But, normally it's impossible to re-size the array with java. So we create new array and copy contents of source array when we need to re-size the array.

Solution for you:

int i = 0;//line count of csv
String[][] data = new String[0][];//csv data line count=0 initially
while ((thisLine = myInput.readLine()) != null) {
    ++i;//increment the line count when new line found

    String[][] newdata = new String[i][2];//create new array for data

    String strar[] = thisLine.split(";");//get contents of line as an array
    newdata[i - 1] = strar;//add new line to the array

    System.arraycopy(data, 0, newdata, 0, i - 1);//copy previously read values to new array
    data = newdata;//set new array as csv data
}

Create test to view csv data:

for (String[] strings : data) {
    for (String string : strings) {
        System.out.print("\t" + string);
    }
    System.out.println();
}

Output:

Id  name
E1  Tim
A1  Tom

Solution 3:[3]

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<String[]> lines = new ArrayList<>();
        for (String line = br.readLine(); line != null; line = br.readLine()) {
            lines.add(line.split(";"));
        }
        return lines.toArray(new String[lines.size()][]);
    }
}

Solution 4:[4]

It's better to use an ArrayList of 1D String arrays, instead of a 2D String array.

String fName = "c:\\csv\\myfile.csv";
String thisLine;
FileInputStream fis = new FileInputStream(fName);
DataInputStream myInput = new DataInputStream(fis);
ArrayList<String[]> strar = new ArrayList<String[]>();

while ((thisLine = myInput.readLine()) != null) {
    strar.add(thisLine.split(";"));
}

Note: Also you need to handle the IOException here.

Solution 5:[5]

This is my implemented code:

String fileName = "myfile.csv";
List<List<String>> list = new ArrayList<List<String>>();
BufferedReader br = new BufferedReader(new FileReader(fileName));
String line = br.readLine();
String[] headers = line.split(";");
for(String header: headers) {
    List<String> subList = new ArrayList<String>();
    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.

Solution 6:[6]

i think you should see this code:

  1. After reading csv file.
  2. Read all lines in a list.
  3. Define two arrays, one is one dimension array, second is two dimension array
  4. for loop along to number of records in the csv file (first loop)
  5. break each record into the one dimension array
  6. for loop inside the first loop along to the number of columns in csv file
  7. Assigned each value from the one dimension array into the two dimension array

the code:

    Path path= Paths.get("url_of_csv_file");
    List<String> arr= Files.readAllLines(path);
    String[] arr2; 
    String[][] arr3= new String[records][columns];
    for(int i=0; i<records; i++){
        arr2= arr.get(i).split("\\,");
    for(int j=0; j<columns; j++)
        arr3[i][j]= arr2[j];
    }
    //test case
    for(int i=0; i<records; i++){
        for(int j=0; j<columns; j++)
            System.out.print(arr3[i][j]+"  ");
        System.out.println();
    }    

Solution 7:[7]

    //read the .csv file and store it in a list of string values
    var DataReader = new BufferedReader(new FileReader(csvPath.toString()));
    String line;
    var Arr = new ArrayList<String>();
    while ((line = DataReader.readLine()) != null) {
        Arr.add(line);
    }

    //break each item in the list to a matrix 
    var TwoDimdata = new String[Arr.size()][Arr.get(0).toString().split(",").length];
    for (var i = 0; i < TwoDimdata.length; i++) {
        for (var j = 0; j < TwoDimdata[0].length; j++) {
            var arr = Arr.get(i).split(",");
            TwoDimdata[i][j] = arr[j];
        }
    }

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ug_
Solution 2 Stevoisiak
Solution 3 Flown
Solution 4 IsuruJ
Solution 5 Stevoisiak
Solution 6 MOHAMMED RIYAD MAHMOUD ALEIADE
Solution 7 MOHAMMED RIYAD MAHMOUD ALEIADE