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
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.
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.
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);
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With