简体   繁体   中英

Dynamic read from file using java String.split

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?

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM