简体   繁体   中英

Reading a .csv file using string.split method

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. :)

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) ):

  • It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space ( '\\u00A0', '\\u2007', '\\u202F').
  • It is '\\t', U+0009 HORIZONTAL TABULATION.
  • It is '\\n', U+000A LINE FEED.
  • It is '\\u000B', U+000B VERTICAL TABULATION.
  • It is '\\f', U+000C FORM FEED.
  • It is '\\r', U+000D CARRIAGE RETURN.
  • It is '\\u001C', U+001C FILE SEPARATOR.
  • It is '\\u001D', U+001D GROUP SEPARATOR.
  • It is '\\u001E', U+001E RECORD SEPARATOR.
  • It is '\\u001F', U+001F UNIT SEPARATOR.

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

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

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

PS: I am assuming you manually changed the data in CSV 'once'. Please ignore if not the case.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM