java - 使用 CSVBeanReader 忽略不需要的列

标签 java supercsv

我希望这里的好心人可以帮助我解决我的 CSV 问题。我只需要读取我正在使用的 CSV 中的前 3 列。我无法控制 CSV 文件的列数,并且没有可用的标题。我尝试使用 CSVBeanReader ( https://super-csv.github.io/super-csv/examples_partial_reading.html ) 进行部分读取,但我不断收到“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

最佳答案

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

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 列为空。

从 header 和处理器中删除 6 个空值可以解决该问题。

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

beanReader.getHeader(true);

关于java - 使用 CSVBeanReader 忽略不需要的列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51046088/

相关文章:

java - SuperCSV 和推土机

java - IllegalStateException java httpclient

java - 使用 MaltParser engmalt 进行解析

java - 未上传数据,但使用 java 在 bigquery 加载作业中作业状态为 DONE

带有未转义引号的 Java CSV 解析器

java - SuperCSV - 将多列解析为列表

supercsv - 用逗号作为小数点分隔符解析双 superCSV?

java - Android 中的外部 JAR 错误

java - 如何更改websphere监听端口

java - 排除 super csv CsvBeanWriter 中的空字段