I'm trying to parse a csv file. A typical line looks like this:
7,118.2722833,98.61084463,94.36895546,,
The problem I'm having is that when I split the line, I'm only getting an array length of 4. I would like to have the fifth and sixth elements of the array return null, but I'm getting an index out of bounds error.
Here is a reduced version of the code:
BufferedReader br = new BufferedReader(new FileReader("FileName"));
String line = "";
String[] datum = new String[6];
while ((line = br.readLine()) != null) {
datum = line.split(",");
if (datum[5] != "") {
//some statements
}
}
Any idea why it's ignoring the last 2 commas?
The split
method without any arguments will discard any trailing null
elements. Pass a negative limit
to split
, and it will return an array with trailing null
elements intact.
datum = line.split(",", -1);
Also, don't use !=
to see if it's the empty string; use
if (!("".equals(datum[5]))) {
Array index starts from 0, if you want 5th element you need to do datum[4]
instead of datum[5]
7 --------------0
118.2722833-----1
98.61084463-----2
94.36895546-----3,
----------------4
我建议阅读有关方法java.lang.String.split(String regex, int limit)
的limit
参数的信息
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.