1

So basically I'm reading a text file that has a bunch of lines. I need to extract certain lines from the text file and add those specific lines into string array. I've been trying to split each newLine with: "\n" , "\r". This did not work. I keep getting this error as well:

Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 1 at A19010.main(A19010.java:47)

Here is the code:

Path objPath = Paths.get("dirsize.txt");
    if (Files.exists(objPath)){

     File objFile = objPath.toFile();
     try(BufferedReader in = new BufferedReader(
                             new FileReader(objFile))){
          String line = in.readLine();

           while(line != null){

            String[] linesFile = line.split("\n");
            String line0 = linesFile[0];
            String line1 = linesFile[1];
            String line2 = linesFile[2];



            System.out.println(line0 + "" + line1);
            line = in.readLine();
           }

        }
         catch(IOException e){

             System.out.println(e);
         }

    }
    else
    {
      System.out.println(
              objPath.toAbsolutePath() + " doesn't exist");
    }
oxxi
  • 452
  • 3
  • 11
  • 28

6 Answers6

3
String[] linesFile = new String[] {line}; // this array is initialized with a single element
String line0 = linesFile[0]; // fine
String line1 = linesFile[1]; // not fine, the array has size 1, so no element at second index
String line2 = linesFile[2];

You're creating a String[] linesFile with one element, line, but then trying to access elements at index 1 and 2. This will give you an ArrayIndexOutOfBoundsException

You're not actually splitting anything here. in.readLine();, as the method says, reads a full line from the file.

Edit: You can add lines (Strings) dynamically to a list instead of an array, since you don't know the size.

List<String> lines = new LinkedList<String>(); // create a new list
String line = in.readLine(); // read a line at a time
while(line != null){ // loop till you have no more lines
    lines.add(line) // add the line to your list
    line = in.readLine(); // try to read another line
}
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • Ok, I understand now why I get the error. So what would be the best way to split or add each line of the text file to a string array? – oxxi Apr 19 '13 at 19:07
  • @oxxi Since you are reading each line, just add the `line` you read, to the array. However, since you don't know how many lines you might have, it might be better to use a `LinkedList` to add the lines to. Take a look at the edit. – Sotirios Delimanolis Apr 19 '13 at 19:54
  • ok `LinkedList<>` worked for me. I was able to implement and access the text in the lines I wanted. Just though it would work with a normal string array. Thanks for the help. – oxxi Apr 19 '13 at 21:55
  • @oxxi The problem with a String array (or any array for that matter) is that once you've initialized it, you can't resize it. If you realize you need more space, you have to create a new and bigger array, copy over all the elements and use the new one. – Sotirios Delimanolis Apr 19 '13 at 22:40
3

readLine() method reads a entire line from the input but removes the newLine characters from it. When you split the line on \n character, you will not find one in the String. Hence, you get the exception.

Please, refer the answer in this link for more clarity.

Community
  • 1
  • 1
Ankur Shanbhag
  • 7,746
  • 2
  • 28
  • 38
0

You are initializing your String array with 1 element, namely line. linesFile[0] is therefore line and the rest of your array is out of bounds.

Davey Chu
  • 2,174
  • 2
  • 14
  • 24
0

Try this:

String[] linesFile = line.split("SPLIT-CHAR-HERE");
if(linesFile.length >= 3)
{
            String line0 = linesFile[0];
            String line1 = linesFile[1];
            String line2 = linesFile[2];
// further logic here
}else
{
//handle invalid lines here
}
harsh
  • 7,502
  • 3
  • 31
  • 32
0

You are using array to store the strings. Instead use ArrayList from Java as ArrayList are dynamically growing. after your reading operation completes convert it into array.

    String line = in.readLine();
      ArrayList<String> str_list = new ArrayList<String>();
      String[] strArr = new String[str_list.size()];

           while(line != null){
             str_list.add(line);  
             line = in.readLine();
           }
    // at the end of the operation convert Arraylist to array
return   str_list.toArray(strArr);
Alpesh Gediya
  • 3,706
  • 1
  • 25
  • 38
0

The issue here is that you are creating a new String array every time your parser reads in a new line. You then populate only the very first element in that String array with the line that is being read in with:

String[] linesFile = new String[] {line};

Since you create a new String[] with one element every single time your while loop runs from the top, you lose the values it stored from the previous iteration.

The solution is to use new String[]; right before you enter the while loop. If you don't know how to use ArrayList, then I suggest a while loop like this:

int numberOfLine = 0;
while (in.readLine() != null)
{
    numberOfLine++;
}
String linesFile = new String[numberOfLine];

This will let you avoid using a dynamically resized ArrayList because you know how many lines your file contains from the above while loop. Then you would keep an additional counter (or resuse numberOfLine since we have no use for it anymore) so that you can populate this array:

numberOfLine = 0;
in = new BufferedReader(new FileReader(objFile)); // reset the buffer
while ((String line = in.readLine()) != null)
{
    linesFile[numberOfLine] = line;
    numberOfLine++;
}

At this point linesFile should be correctly populated with the lines in your file, such that linesFile[i] can be used to access the i'th line in the file.

huu
  • 7,032
  • 2
  • 34
  • 49
  • So, I'm going to need 2 while loops? – oxxi Apr 19 '13 at 20:10
  • The first `while` loop is purely to count the number of lines in the file. If you know this beforehand, then it isn't necessary. Additionally, you can avoid the first `while` loop by using an `ArrayList` instead of `String[]`, but the trade-off is that this requires more memory. – huu Apr 19 '13 at 20:19
  • I can see how it could work, but I couldn't figure out how to implement your code correctly with mine. – oxxi Apr 19 '13 at 21:59