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"); } 
4
  • Where are you splitting the line..? Commented Apr 19, 2013 at 18:45
  • I had this before: String[] linesFile = line.split("\n"); Commented Apr 19, 2013 at 18:50
  • 1
    After you have done the BufferedReader.readLine() you have read the line. What are you then trying to do? Split it into words? Commented Apr 19, 2013 at 18:50
  • I want to split each newline of text in the file and add it to a string array so I can latter extract certain parts from the line. Commented Apr 19, 2013 at 18:55

6 Answers 6

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 } 
Sign up to request clarification or add additional context in comments.

4 Comments

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 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<String> to add the lines to. Take a look at the edit.
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 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.
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.

Comments

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.

Comments

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 } 

1 Comment

could the "SPLIT-CHAR-HERE" be "\n". I'm on a mac by the way so would it be "\r"?
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); 

Comments

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.

3 Comments

So, I'm going to need 2 while loops?
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<String> instead of String[], but the trade-off is that this requires more memory.
I can see how it could work, but I couldn't figure out how to implement your code correctly with mine.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.