为什么java抛出异常java.lang.ArrayIndexOutOfBoundsException:1

时间:2015-04-01 14:03:17

标签: 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() + ","
                    + book.getDate() + "\n";
            print.println(str);
        }
    } catch (Exception e) {
    }

}

此代码从a文件写入数据并将其插入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

有什么问题?

1 个答案:

答案 0 :(得分:1)

执行以下操作:

  1. 检查文件的内容,每行有多少','char,它应该至少有2个
  2. 检查数组的大小,每次读取迭代时应至少为3,因为您正在访问array[2]
  3. 似乎某个行或迭代的数组没有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 如果应用程序仍然触发相同的错误,那么它将是其他内容。