Hi, i am having trouble reading a csv file into a 2D array
my code so far is as follows:
File file = null;
int returnVal;
String criteria[][] = null;
JFileChooser fc = new JFileChooser();
returnVal = fc.showOpenDialog(this);
String line = "";
int row = 0, col = 0;
int finalrows = 0, finalcols = 0;
BufferedReader in = null;
if(returnVal == JFileChooser.APPROVE_OPTION){
file = fc.getSelectedFile();
try{
in = new BufferedReader(new FileReader( file ));
}catch(Exception e){
e.printStackTrace();
}
}
try{
//this loop is used to determine the max number of rows and cols i need for the array
while((line = in.readLine()) != null){
StringTokenizer st = new StringTokenizer(line,",");
while (st.hasMoreTokens()){
//get next token and store it in the array
col++;
if(finalcols < col){
finalcols = col;
}
}
col = 0;
row++;
if(finalrows < row){
finalrows = row;
}
}
in.reset();
//set the array to the max number of rows and cols
criteria = new String[finalrows][finalcols];
while((line = in.readLine()) != null){
System.out.println(line);
StringTokenizer st = new StringTokenizer(line,",");
while (st.hasMoreTokens()){
//get next token and store it in the array
System.out.println(st.nextElement());
criteria[row][col] = st.nextToken();
col++;
}
col = 0;
row++;
}
in.close();
}catch(Exception e){
e.printStackTrace();
}
for(int i = 0; i < criteria.length; i++){
for(int j = 0; j < criteria[0].length; j++){
System.out.print(criteria[i][j] + " ");
}
System.out.println();
}
Doea anyone have an idea of what is not working or what i should change? please help.
!--removed tag-->
No one has replied yet! Why not be the first?
Sign in or Join us (it's free).