I'm banging my head against a wall about a program I'm trying to complete. I'm sure the answer is simple but I just can't figure out the solution.
When I write to the csv file it works but when reading from it, if there is more than 3 objects in the csv file, I get the ArrayIndex error but three or less and it throws no error.
Below is my code for writing to the file:
void saveDataToFile() {
String op = "";
try {
FileWriter fw = new FileWriter(filename);
for (int i =0 ; i< library.length ; i++)
if(library[i]!=null)
fw.write(library[i].getDetailsCSV().toString()+"\n");
fw.write(op.toString());
fw.close();
}
catch(Exception e) {
System.out.println("ERROR : "+e);
}
System.out.println("saveDataToFile()");
}
Below is the code for reading the file:
void loadDataFromFile() {
try{
File fi = new File(filename);
FileReader fr = new FileReader(fi);
char[] buffer = new char[(int)fi.length()];
fr.read(buffer);
fr.close();
String all = new String(buffer);
String[] ip = all.split("\n");
for (int i=0; i<ip.length; i++){
String[] op = ip[i].split(",");
String author = op[0];
String title = op[1];
int isbn = Integer.parseInt(op[2]);
String s = op[3];
boolean h = Boolean.parseBoolean(op[3]);
for(int j=0; j<op.length; j++){
if(author.equals("Dickens"))
library[i] = new title(author,isbn);
else if(author.equals("Lumas"))
library[i] = new title(author,isbn,s);
else if(author.equals("Orwell"))
library[i] = new title(author,isbn,h);
}
}
}
catch(Exception e) {
System.out.println("ERROR : "+e);
}
System.out.println("loadDataFromFile()");
}
The library[] array is size 10. I've tried a System.out.println(op.length); and System.out.println(ip.length); from the read method and ip.length is 10 and op.length is 3 (regardless of how many objects have actually been saved to the csv file i.e. even if it's full).
I'd really appreciate if anyone can see what I am obviously missing!