0

我正在使用 Springboot + OpenCSV 解析具有 120 列的 CSV(示例1)。我上传文件处理每一行,如果出现错误,返回一个类似的 CSV(比如 errorCSV)。此 errorCSV 将仅错误输出包含 120 个原始列和 3 个附加列的行,以获取有关问题的详细信息。示例错误文件2

我使用了基于注释的处理,并且 bean 填充得很好。但我需要按照它们在 csv 中出现的顺序获取标题名称。这个特定的部分非常具有挑战性。然后在解析过程中捕获异常和原始数据。以后可以将两者一起用于编写 CSV。

CSVReaderHeaderAware headerReader;
headerReader = new CSVReaderHeaderAware(reader);
try {
        header = headerReader.readMap().keySet();
} catch (CsvValidationException e) {
        e.printStackTrace();
}

但是标题顺序混乱,无法获取标题索引。CSVReaderHeaderAware 内部使用 HashMap 的原因。为了解决这个问题,我构建了我的自定义类。它是 CSVReaderHeaderAware 3的副本,除了我使用了 LinkedHashMap

public class CSVReaderHeaderOrderAware extends CSVReader {
    private final Map<String, Integer> headerIndex = new LinkedHashMap<>();
}

……

 // This code cannot be done with a stream and Collectors.toMap()
    // because Map.merge() does not play well with null values. Some
    // implementations throw a NullPointerException, others simply remove
    // the key from the map.
 Map<String, String> resultMap = new LinkedHashMap<>(headerIndex.size()*2);

它完成了这项工作,但是想要检查这是否是最好的方法,或者你能想出一种更好的方法来获取标题名称和失败的值并写入 csv。

我提到了以下链接,但没有得到太多帮助 如何从 opencsv 中的特定标题中读取?

4

0 回答 0