gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-02 11:05:01 25 4
gpt4 key购买 nike

我希望这里的好心人可以帮助我解决我的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com