0

I've got a file that contains something like this:

Hello;my name;is Marco
I want;some cheese
Hi
this;is;a;test

As you can see I have some words which are separated by a ;. Number of elements in the rows are not fixed, so I need a dynamic way of reading each row. I tried using String split method, this way for each row that I'm reading:

String supp = "";
while((supp = read.split(";")[i]) != null){
     i++;
}
System.out.println("Number of elements: " + i);

But of course it's not working (ArrayIndexOutOfBoundsException).

How can I read the whole file dynamically?

abierto
  • 1,447
  • 7
  • 29
  • 57
  • 1. read each line 2. split each line into a splitArray 3. loop from 0 to splitArray.length 4. go back to 1. – assylias Feb 04 '13 at 11:08

1 Answers1

3

split gives you an array so you should use it:

String[] parts = read.split(";");
System.out.println("Number of elements: " + parts.length);

You shouldn't check size of array using indexing. Each array has length field that gives you it's size.

If you need to read file you can use BufferedReader that has handy method for reading file line by line. Check this question: How to read a large text file line by line using Java?

Community
  • 1
  • 1
Mikita Belahlazau
  • 15,326
  • 2
  • 38
  • 43