Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
948 views
in Technique[技术] by (71.8m points)

arrays - Parse CSV file in java, and delaing with empty values

I am parsing a CSV file into my program, spliting the values at the , element, and it's working fine, except for when I have lines that have missing values.

The parser is working like this:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class CsvReader
{
    private static final String DELIMITER = ",";
    private final BufferedReader br;
    private final String path;

    public CsvReader(final String path) throws IOException
    {
        this.path = path;
        this.br = new BufferedReader(new FileReader(path));
    }

    public String[] nextLine() throws IOException
    {
        final String line = br.readLine();
        return (line == null) ? new String[0] : line.split(DELIMITER);
    }
}

The lines of data look like this (one line as an example):

J1024205,5028197000004,1,,00,20150603,,Accessories,Factory Test Article (m),ENG,010,110,5,T1,99,99,,,99,99,99,ZZ,ZZ,,5028197242053,30,35028197242054,6,,,OPZ848,3013607800239,OPZ848,,,,50,,

Most of the lines in the file complete with this: 50,85028197242127,8640

But on some lines, the data is missing, so it ends like this: 50,,

When the file is being processed, these lines are causing a java.lang.ArrayIndexOutOfBoundsException.

How can I best deal with this, if I know that the numbers of objects in the file will remain constant?

I've been told that I need to replace empty values with a null value.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

From the Javadoc of String.split(regex)

This method works as if by invoking the two-argument split method with the given expression and a limit argument of zero. Trailing empty strings are therefore not included in the resulting array.

So, in your case, when the string ends with ,,, empty strings wont be part of the resultant array.

To Fix: Use this variant of split

line.split(DELIMITER, -1);

This will include all trailing empty strings. So you won't get an exception.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to WuJiGu Developer Q&A Community for programmer and developer-Open, Learning and Share
...