Hello,

I am writing a small java code which read from a text file line by line and parses each read line(hash seperated).

Here is the code snippet:
in =new BufferedReader(new InputStreamReader(new FileInputStream("file.txt")));
while((linedata =in.readLine())!=null)
{
     System.out.println("Linedata: "+linedata);
     strparse = linedata.split("#");
     line = strparse[1];
     System.out.println("Line Number:"+strparse[1]);
}

the data in the sample file is:
#64#080517#090002#9999999999#1#9999999999#N#ABC#-1#QQQ#
#63#080517#090002#9999999999#1#99999999999#N#EDF#-1#WWW#
#67#080517#090002#9999999999#1#99999999999#N#FGH#-1#RRR#

The output after running the java code is:
Linedata:#64#080517#090002#9999999999#1#9999999999#N#ABC#-1#QQQ#
Line Number: 64
Linedata:
java.lang.ArrayIndexOutOfBoundsException: 1

Please advice.

Regards.

Recommended Answers

All 5 Replies

From this output:

Linedata:
java.lang.ArrayIndexOutOfBoundsException: 1

I believe that one of the lines is empty. As you can see nothing is printed after the "Linedata:". So probably you are doing split("#") to an empty line. Therefor the table will have size 0 or 1 (I don't know exactly), but the point is that the array strparse does not have 2 elements so you can execute: strparse[1].
You should check if it is OK to do a strparse[1] to the array:

if (strparse.length>1) //do stuff with the strparse[1]

The exception should help you solve this problem since it says: Array Index Out Of Bounds Exception 1. The index "1" you used for the array is out of bounds. Doesn't have that many elements. Plus the line: Linedata: shows you that you have an empty line

I agree with u that exception is caused by split function. As per my understanding Readline function should idly read on complete line, but here readline function is reading once a complete line and then a blank line. If I skip that blank line by putting some length checks it finely read the next line. But why is the readline API reading a blank line the second time?

Why don't you try this instead:

String linedata = in.readLine();
while( linedata!=null )
{
    //
    //
    // 

   linedata = in.readLine();
}
Well this didnt make any difference.
Well this didnt make any difference.

The only think I can think of is to try this:

FileReader fileReader=new FileReader("file.txt");
BufferedReader buffer=new BufferedReader(fileReader);

By the way: Do you close BufferedReader? Probably you do or else you wouldn't be able to read in the first place, but check it just in case:

Do
in.close();
after you finish reading out of the while()

Also close fileReader if you try my suggestion

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.