简体   繁体   English

使用Java String.split从文件动态读取

[英]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 ; 正如您所看到的,我有一些单词用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 split方法,这种方式适用于我正在读取的每一行:

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

But of course it's not working ( ArrayIndexOutOfBoundsException ). 但是,当然它不起作用( ArrayIndexOutOfBoundsException )。

How can I read the whole file dynamically? 如何动态读取整个文件?

split gives you an array so you should use it: split给您一个数组,因此您应该使用它:

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. 每个数组都有一个length字段,可以为您提供大小。

If you need to read file you can use BufferedReader that has handy method for reading file line by line. 如果您需要读取文件,可以使用BufferedReader ,它具有方便的方法来逐行读取文件。 Check this question: How to read a large text file line by line using Java? 检查以下问题: 如何使用Java逐行读取大文本文件?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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