Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting CSV File Into 2D Array

Tags:

java

arrays

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

like image 835
Mvz Avatar asked Oct 09 '15 09:10

Mvz


People also ask

How do I convert a CSV file to a 2D array?

Line 1: We import the NumPy library. Line 3-4: We open the sampleCSV file and we pass both CSVData and the delimiter to NumPy np. genfromtxt () function, which returns the data into a 2D array. Line 6: We finally print the result which shows that now our CSV data converted into a 2D array.

How do I convert a CSV file to an array in Python?

np.genfromtxt() You can convert a CSV file to a NumPy array simply by calling np. genfromtxt() with two arguments: the filename and the delimiter string. For example, the expression np. genfromtxt('my_file.


2 Answers

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);
like image 136
ug_ Avatar answered Oct 25 '22 17:10

ug_


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
like image 41
Channa Jayamuni Avatar answered Oct 25 '22 18:10

Channa Jayamuni