使用CSVBeanReader忽略不需要的列

时间:2018-06-26 15:05:44

标签: java supercsv

我希望这里的善良人士能帮助我解决CSV情况。我只需要阅读我使用的CSV的前3列。我无法控制CSV文件的列数,也没有标题可用。我尝试将部分读取与CSVBeanReader(similar post)配合使用,但始终收到“ nameMapping数组和读取的列数”错误。我想问一下部分阅读示例是否适用于我当前使用的supercsv版本2.4.0。请参阅下面的代码,该代码类似于部分读取的示例

public class MainPartialRead {

public void partialRead() throws Exception {
    ICsvBeanReader beanReader = null;
    String csv_filename = "test2.csv";
    try {
        beanReader = new CsvBeanReader(new FileReader(csv_filename), CsvPreference.STANDARD_PREFERENCE);
        beanReader.getHeader(true); // skip past the header (we're defining our own)
        System.out.println("beanreader Length: " + beanReader.length());

        // only map the first 3 columns - setting header elements to null means those columns are ignored
        final String[] header = new String[]{"column1", "column2", "column3", null, null, null, null, null,
            null, null};

        // no processing required for ignored columns
        final CellProcessor[] processors = new CellProcessor[]{new NotNull(), new NotNull(),
            new NotNull(), null, null, null, null, null, null, null};

        beanCSVReport customer;
        while ((customer = beanReader.read(beanCSVReport.class, header, processors)) != null) {
            System.out.println(String.format("lineNo=%s, rowNo=%s, customer=%s", beanReader.getLineNumber(),
                    beanReader.getRowNumber(), customer));
        }
    } finally {
        if (beanReader != null) {
            beanReader.close();
        }
    }

}

这是我正在使用的示例CSV文件:

466,24127,abc,53516
868,46363,hth,249

1 个答案:

答案 0 :(得分:1)

您没有提及完整的错误消息。

Exception in thread "main" java.lang.IllegalArgumentException: the nameMapping array and the number of columns read should be the same size
(nameMapping length = 10, columns = 4)

由此可以很清楚地看出问题所在。 csv文件中只有4列,但是您提到了10列的映射,其中7列为空。

从标头和处理器中删除6个空值可以解决此问题。

要注意的另一点。以下代码跳过第一行,假设它是您指示的标题,但实际上它不是标题行。您不应该调用此方法。

beanReader.getHeader(true);
相关问题