为什么java抛出异常java.lang.ArrayIndexOutOfBoundsException:1
问题描述:
我有一个代码从文件中读取数据并将其插入到数据库中。为什么java抛出异常java.lang.ArrayIndexOutOfBoundsException:1
该代码将数据写入文件。
public void save(Collection<Book> b) {
try (PrintWriter print = new PrintWriter(this.file);) {
for (Book book : b) {
String str = book.getName() + "," + book.getAuthor() + ","
+ book.getDate() + "\n";
print.println(str);
}
} catch (Exception e) {
}
}
此代码写入文件中的数据并将其插入到db中。
try(Reader reader = new FileReader(this.file);
BufferedReader br = new BufferedReader(reader)) {
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/myBook", this.userName,
this.pass);
Statement statement = connection.createStatement();
String str;
while((str = br.readLine()) != null){
String[] array = str.split(",");
statement.executeUpdate("Insert Into myBook.book (name,author,pubDate) values('"+array[0]+"', '"+ array[1]+"', '"+array[2]+"')");
}
}
但它抛出异常
java.lang.ArrayIndexOutOfBoundsException
有什么不对?
答
执行以下操作:
- 检查文件的内容,有多少“”字符它在每一行,它应该有至少2
- 检查数组的大小,它应该在每次读取迭代至少3次,因为您正在访问
array[2]
似乎某行或迭代的数组没有3个项目,可能是一个或两个。
例如:
line 1: aaa,bbb,ccc //2 ',' => array={"aaa","bbb","ccc"} this is fine
line 2: ddd,eee //1 ',' => array={"ddd","eee"} this causes the
// exception since array[2] does not exist NULL
line 3: empty //0 ',' => array={} this causes the exception
如果你不知道发生了什么运行下面的代码:
try(Reader reader = new FileReader(this.file);
BufferedReader br = new BufferedReader(reader)) {
connection = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/myBook", this.userName,
this.pass);
Statement statement = connection.createStatement();
String str;
while((str = br.readLine()) != null&&str.split(",").length>=3){
String[] array = str.split(",");
statement.executeUpdate("Insert Into myBook.book
(name,author,pubDate) values('"+array[0]+"', '"+ array[1]+"', '"+array[2]+"')");
}
}
如果没有错误,上面的代码运行,那么至少有一行没有2','chars 如果应用程序仍然发射相同的错误,那么它将是别的东西。
+0
它包含2','字符,我检查了数组,它的大小是3 – Arno 2015-04-01 14:21:43
因为'array'只有一个元素 – gefei 2015-04-01 14:05:06
输入不包含'“,”'。它应该有两个或更多的能够使用'array [1]'和'array [2]'。 – Bubletan 2015-04-01 14:06:12
不,它包含绝对是我的行在文件中 Chenty,Rafi,01.25.1850 Kaytser,Rafi,01.25.1855 – Arno 2015-04-01 14:07:36