jdbc - Why java throws exception java.lang.ArrayIndexOutOfBoundsException: 1 -
i have code reads data file , inserts database.
this code writes data file.
public void save(collection<book> b) { try (printwriter print = new printwriter(this.file);) { (book book : b) { string str = book.getname() + "," + book.getauthor() + "," + book.getdate() + "\n"; print.println(str); } } catch (exception e) { } }
this code writes data file , inserts 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 mybook.book (name,author,pubdate) values('"+array[0]+"', '"+ array[1]+"', '"+array[2]+"')"); } }
but throws exception
java.lang.arrayindexoutofboundsexception
what wrong?
do following:
- check content of file, how many ',' char have in each line, should have @ least 2
- check size of array, should @ least 3 in each read iteration, since accessing
array[2]
it seems array @ line or iteration doesn't have 3 items, maybe 1 or two.
example:
line 1: aaa,bbb,ccc //2 ',' => array={"aaa","bbb","ccc"} fine line 2: ddd,eee //1 ',' => array={"ddd","eee"} causes // exception since array[2] not exist null line 3: empty //0 ',' => array={} causes exception
if not sure of happening run following code:
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 mybook.book (name,author,pubdate) values('"+array[0]+"', '"+ array[1]+"', '"+array[2]+"')"); } }
if above code run without error @ least 1 line doesn't have 2 ',' chars if application still firing same error else.
Comments
Post a Comment