我正在为我想要完成的一个项目而碰壁。我确信答案很简单,但我就是想不出解决方案。
当我写入 csv 文件时,它可以工作,但是当从中读取时,如果 csv 文件中有超过 3 个对象,我会收到 ArrayIndex 错误,但只有 3 个或更少,并且不会引发错误。
下面是我写入文件的代码:
无效 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()");
}
下面是读取文件的代码:
无效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()");
}
library[] 数组的大小为 10。我尝试过 System.out.println(op.length);和 System.out.println(ip.length);从 read 方法中,ip.length 为 10,op.length 为 3(无论实际有多少对象已保存到 csv 文件,即即使它已满)。
如果有人能看到我明显缺少的东西,我将非常感激!
最佳答案
我猜这个循环正在破坏它:
for(int j=0; j<op.length; j++){
if(make.equals("Ford"))
cars[i] = new Ford(model,year);
else if(make.equals("Mazda"))
cars[i] = new Mazda(model,year,colour);
else if(make.equals("Toyota"))
cars[i] = new Toyota(model,year,h);
}
如果你有超过 3 行,这个循环将会失败,因为你使用的是 i 而不是 j。不确定这个循环试图做什么,但那部分肯定会失败。
此外,如果 op.length 为 3,则索引 3 将不存在,因为 Java 数组的索引是从 0 而不是 1。
关于Java读取.csv文件并获取java.lang.ArrayIndexOutOfBoundsException : 3 and don't know why,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16024537/