关于使用超级csv bean读取器的错误

时间:2015-12-22 08:39:52

标签: java supercsv

我添加了以下依赖项:

    <dependency>
    <groupId>net.sf.supercsv</groupId>
    <artifactId>super-csv</artifactId>
    <version>2.4.0</version>
    </dependency>

    private final static String[] COLS = { "col1", "col2", "col3", "col4", "col5",
        "col6", "col7", "col8", "col9", "col10", "col11",
        "col12", "col13", "col14" };


    private final static String[] TEMP_COLS = {"col1", "col2", "col3", "col4", "col5",
        "col6", "col7", "col8", "col9", "col10", "col11",
        "col12", "col13"};

以下是我建立读者的方式。

protected CsvPreference csvPref = CsvPreference.STANDARD_PREFERENCE;
 protected String encoding = "US-ASCII";
InputStream is = fs.open(path);
      BufferedReader br = new BufferedReader(new InputStreamReader(is, encoding));
      ICsvBeanReader csvReader = new CsvBeanReader(br, csvPref);

作为bean阅读器的一部分,我有以下代码:

Selections bean = null;

    try{
        bean = reader.read(Selections.class, Selections.getCols());
        }catch(Exception e){    
   // bean = reader.read(Selections.class, Selections.getTempCols());
   // slf4j.error(bean.getEventCode() + bean.getProgramId());
    slf4j.error("Error Logged for bean because of COLUMNS MISMATCH");
        }

在上面的代码中,抛出异常:

java.lang.IllegalArgumentException:the nameMapping array and the number of columns read should be the same size (nameMapping length = 14, columns = 13))

我不确定导致此异常是什么。即使所有记录都有14列,我也会在某些记录上抛出此异常(我已经通过使用脚本验证了这一点,我甚至创建了一个模式并上传了文件有14列)。在7,000,000条记录中,2,100,000条记录了这个问题。

为了调试导致此问题的记录,我对代码进行了以下更改。

Selections bean = null;

        try{
            bean = reader.read(Selections.class, Selections.getCols());
            }catch(Exception e){    
        bean = reader.read(Selections.class, Selections.getTempCols());
        slf4j.error(bean.getEventCode() + bean.getProgramId());
        slf4j.error("Error Logged for bean because of COLUMNS MISMATCH");
            }

现在,上述更改正在抛出:java.lang.IllegalArgumentException: the nameMapping array and the number of columns read should be the same size (nameMapping length = 13, columns = 14)

我不知道为什么开放的csv阅读器行为如此奇怪。如果列数不是14,则会导致异常,并且在尝试读取它以打印详细信息时会出现异常,它表示列数为14。

请帮我调试这个问题。如有需要,我将更新有关该问题的更多详细信息。请告诉我。

2 个答案:

答案 0 :(得分:0)

在深入了解超级csv来源并确认您可以使用14列coreectly上传后,我建议您寻找Super CSV的替代品。

我的建议:查看Apache Commons CSV

此库还支持迭代方法,因此您不需要在内存中包含7.000.000条记录。

答案 1 :(得分:0)

最后我解决了问题,问题是由于我在CSV偏好设置中给出的columnquote模式字符。

new CsvPreference.Builder('"', '\u0001', "\r\n").build()

我的传入数据有"作为数据的一部分。当我用一个永远不会成为传入数据一部分的字符替换带引号的列时,问题得到了解决。

我不是它的专家,这是因为我的无知和超级scv没有错。我相信super-csv是一个很好的探索和使用的API。

要了解有关列报价模式的更多信息,请参阅其API。   https://super-csv.github.io/super-csv/apidocs/org/supercsv/quote/ColumnQuoteMode.html