Reputation: 1250
I have a .csv file which consists entry in following format:-
question,option1,option2,option3,option4,answer
I want to read this .csv file and insert data in a table. I am using string.split method for doing this and it works fine for eg:-
String a="hi,a,b,c,d,e";
String[] b=a.split(",");
output is:-
b[0]=hi
b[1]=a
b[2]=b
b[3]=c
b[4]=d
b[5]=e
but when i use space in between it gives me an error: for eg:-
String a="hi how are you,a,b,c,d,e";
String[] b=a.split(",");
I am using this concept in a servlet which stores the values in database. Here is the servlet code:-
File file=new File(path2);
Scanner inputstream=new Scanner(file);
while(inputstream.hasNext()){
String data=inputstream.next();
String[] val=data.split(",");
String sql4="insert into "+name+"(question,option1,option2,option3,option4,answer) values('"+val[0]+"','"+val[1]+"','"+val[2]+"','"+val[3]+"','"+val[4]+"','"+val[5]+"')";
s.execute(sql4);
}
I am getting Array index out of bound exception.
Please help.
Thankyou. :)
Upvotes: 1
Views: 4251
Reputation: 31253
By default, space
is one of the delimiters. This makes you have tons of small arrays instead of arrays with exactly 5 elements. Hence your ArrayOutOfBounds if you assumed that every line contained exactly 5 elements.
Specify the delimiter like this :
Scanner inputstream=new Scanner(file);
inputstream.useDelimiter("\n");
Edit : This code shows you the default delimiter :
Scanner inputstream=new Scanner(file);
System.out.println("Delimiter : "+inputstream.delimiter().toString());
Output :
\p{javaWhitespace}+
This includes (according to javadoc of Character#isWhiteSpace(char ch)):
Upvotes: 2
Reputation: 719
Try this code,
File file = new File(path2);
String data = new Scanner(file).useDelimiter("\\A").next();
String[] val = data.split(",");
String sql4 = "insert into " + name + "(question,option1,option2,option3,option4,answer) values('" + val[0] + "','" + val[1] + "','" + val[2] + "','"
+ val[3] + "','" + val[4] + "','" + val[5] + "')";
s.execute(sql4);
If you are iterating over the stream than you should split the string after completely reading the stream . splitting it in every cycle may not result same output since you may not have full data yet.
More explanation on use of scanner class to convert to string - Stupid Scanner Tricks
Upvotes: 1
Reputation: 322
There seems to be no problem with code. It is most likely with your CSV file.
Also, let me take a very silly guess and confirm that when changing your test case in CSV format, you aren't replacing a comma with space, are you...!?
I know i am taking a very silly guess, but trust me, i have done really silly things and had only myself to blame for it :D
P.S: I am assuming you manually changed the data in CSV 'once'. Please ignore if not the case.
Upvotes: 0
Reputation: 271
I don´t see where's the error. Itsearches for the delimiter you pass as parameter (','), so it splits your string in:
b[0]=hi how are you
b[1]=a
b[2]=b
b[3]=c
b[4]=d
b[5]=e
Upvotes: 0