为什么java抛出异常java.lang.ArrayIndexOutOfBoundsException:1
我有一个从文件中读取数据并将其插入数据库的代码 此代码将数据写入文件为什么java抛出异常java.lang.ArrayIndexOutOfBoundsException:1,java,jdbc,Java,Jdbc,我有一个从文件中读取数据并将其插入数据库的代码 此代码将数据写入文件 public void save(Collection<Book> b) { try (PrintWriter print = new PrintWriter(this.file);) { for (Book book : b) { String str = book.getName() + "," + book.getAuthor() + ","
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) {
}
}
但它抛出了一个例外
java.lang.ArrayIndexOutOfBoundsException
怎么了 执行以下操作:
array[2]
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','字符
如果应用程序仍然触发相同的错误,那么它将是另一个错误。因为
数组
只有一个元素输入不包含“,”
。它应该有两个或两个以上的数组才能使用array[1]
和array[2]
。不,它肯定包含我在Chenty,Rafi,01.25.1850 Kaytser,Rafi,01.25.1855文件中的行。你试过调试吗?请给你的问题本身添加任何说明(使用编辑链接)-请不要在评论中。它包含2',“chars和我检查了数组,它的大小是3
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]+"')");
}
}