Java 使用CSVBeanReader忽略不需要的列

Java 使用CSVBeanReader忽略不需要的列,java,supercsv,Java,Supercsv,我希望这里善良的人们能帮助我解决我的处境。我只需要阅读我正在使用的CSV中的前3列。我无法控制CSV文件的列数,也没有可用的标题。我尝试使用CSVBeanReader()进行部分读取,但一直出现“nameMapping数组和读取的列数”错误。我想问一下,部分阅读示例是否适用于我目前使用的supercsv 2.4.0版。请参见下面我使用的代码,该代码与部分读取示例类似 public class MainPartialRead { public void partialRead() throws

我希望这里善良的人们能帮助我解决我的处境。我只需要阅读我正在使用的CSV中的前3列。我无法控制CSV文件的列数,也没有可用的标题。我尝试使用CSVBeanReader()进行部分读取,但一直出现“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文件:

46624127,美国广播公司,53516
86846363,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列为空

从标头和处理器中删除6个空值修复了该问题

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

beanReader.getHeader(true);

示例csv中的头在哪里?遗憾的是没有头。是的,您在代码中的头映射中的观察是正确的,感谢您指出beanReader.getHeader的行为。我更感兴趣的是知道superCSV站点中提供的部分阅读示例(请参阅我问题中的链接)是否与他们站点中提供的一样有效。我尝试复制该示例失败,如我给出的代码所示。我只需要读取我的CSV文件的前3列,其中可能有任意数量的列,而忽略其余的列。我还需要处理器解析这3列以确保有效性。谢谢正如我在回答中所说,部分读取通过输入正确数量的空值来工作。你有7个空值。将其替换为1 null。3个命名列和1个空(忽略)列。它起作用了。现在,如果你的问题是你甚至不知道列的数量,那么你需要读一行并找出答案。在列映射中,传递正确数量的列(命名或空)。我已经运行了你的样本,它的工作。