I am trying to read a csv file which has 3 columns and an unspecified number of rows. I am then trying to take each column and read each into an arrayList of its own. The first column is the name, the second is the score and the third is the difficulty. Any help would be much appreciated. Current code:
public static void main(String[]args) throws IOException{
ReadFile f = new ReadFile();
}
public CSVReader reader;
ReadFile(){
ArrayList myEntries = new ArrayList<>();
ArrayList<String> nameList = new ArrayList<>();
ArrayList<String> scoreList = new ArrayList<>();
ArrayList<String> difficultyList = new ArrayList<>();
try {
reader = new CSVReader(new FileReader("H:\\S6\\AH Computing\\Java Practice\\leaderboard.csv"));
} catch (FileNotFoundException ex) {
Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
}
try {
myEntries.add(reader.readAll());
} catch (IOException ex) {
Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
}
for(int i = 1; i< myEntries.size();i++){
try {
myEntries.add(reader.readNext());
} catch (IOException ex) {
Logger.getLogger(ReadFile.class.getName()).log(Level.SEVERE, null, ex);
}
}
for(int i = 1; i< myEntries.size();i++){
nameList.add((String) myEntries.get(i));
i++;
scoreList.add((String) myEntries.get(i));
i++;
difficultyList.add((String) myEntries.get(i));
}
}
Well there is several problems with your code. First off the CSVReader readAll method reads the entire file and returns a List so in your code change myEntries.add(reader.readAll()); to myEntries.addAll(reader.readAll());
That said now that you have read the entire file into memory there is no need to do a readNext. So remove that entire try/catch.
Now what you have is an List so change
for(int i = 1; i< myEntries.size();i++){
nameList.add((String) myEntries.get(i));
i++;
scoreList.add((String) myEntries.get(i));
i++;
difficultyList.add((String) myEntries.get(i));
}
to
for(int i = 1; i< myEntries.size();i++){
String[] entries = myEntries.get(i);
nameList.add(entries[0]);
scoreList.add(entries[1]);
difficultyList.add(entries[2]);
}
Some typecasting may be necessary.
You can look at the opencsv javadocs at http://opencsv.sourceforge.net/apidocs/index.html for more information.