在java中解析CSV文件,并使用空值进行delaing [英] Parse CSV file in java, and delaing with empty values

查看:683
本文介绍了在java中解析CSV文件,并使用空值进行delaing的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将CSV文件解析到我的程序中,在元素中拆分值,并且它工作正常,除非我有缺少值的行。

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,,

文件中的大多数行都包含: 50,85028197242127,8640

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

但在某些行上,数据丢失了,所以结尾如下: 50 ,,

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

处理文件时,这些行导致 java.lang.ArrayIndexOutOfBoundsException

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.

推荐答案

来自<$ c $的Javadoc c> String.split(正则表达式)


此方法的作用就像通过调用给定表达式和limit参数为零的双参数split方法一样。 结果数组中不包含尾随空字符串

因此,在您的情况下,当字符串以 ,, 结尾,空字符串不会是结果数组的一部分。

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

要修复: 使用此分割变体

line.split(DELIMITER, -1);

这将包括所有尾随空字符串。所以你不会得到例外。

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

这篇关于在java中解析CSV文件,并使用空值进行delaing的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆