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?
splitgives you an array so you should use it:You shouldn’t check size of array using indexing. Each array has
lengthfield that gives you it’s size.If you need to read file you can use
BufferedReaderthat has handy method for reading file line by line. Check this question: How to read a large text file line by line using Java?