Mees van Z Mees van Z - 1 month ago 10
Java Question

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

ug_ ug_
Answer Source

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