Parse the CSV file in Java and delete it with a null value

I'm parsing the CSV file into my program, splitting the value into elements, and it works normally unless I have a line with a missing value

The parser works as follows:

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 data row looks like this (one row as an example):

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

Most of the lines in this file contain: 50850281972421278640

But in some aspects, the data is missing, so the end is as follows: 50,

When processing files, these lines cause Java lang.Arrayindexoutofboundsexception.

How can I best solve this problem if I know that the number of objects in the file will remain the same?

I was told that I needed to replace null values with null values

Solution

From string Javadoc for split (regular expression)

So, in your case, when the string ends with, the empty string will not become part of the result array

To fix: use this split variant

line.split(DELIMITER,-1);

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

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>