You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用Apache Commons CSV获取CSV文件表头前的前置注释

Apache Commons CSV 获取表头前置注释方法

可以直接访问表头前的前置注释,不需要放弃自动表头解析能力。

实现原理

Apache Commons CSV 自动解析表头时,不会丢弃表头行之前的连续注释,这部分注释不会绑定到后续的数据记录上,而是作为表头元数据直接存储在CSVParser实例中,通过专属的getter方法即可获取。

具体操作

在初始化CSVParser之后,直接调用parser.getHeaderComments()方法,就能拿到所有表头之前的前置注释,返回值是List<String>类型,列表元素已经自动去除了注释标记符和前缀空白:

  • 示例中第一行注释; leading会被处理为元素leading
  • 第二行注释; comments会被处理为元素comments

这个方式完全不需要修改setHeader()的自动解析配置,表头自动映射、按列名读取数据的能力完全不受影响。

修改后的可运行示例代码

package com.nowhere;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVParser;
import org.apache.commons.csv.CSVRecord;

import java.io.IOException;
import java.io.Reader;
import java.io.StringReader;
import java.util.List;

public class Main {
    public static void main(String[] args) throws IOException {
        try (Reader reader = new StringReader(DATA); CSVParser parser = CSVParser.parse(reader, FORMAT)) {
            // 获取表头前置注释
            List<String> leadingComments = parser.getHeaderComments();
            System.out.println("前置注释内容:" + leadingComments);
            
            // 原有表头解析、数据遍历逻辑完全正常
            for (CSVRecord rec : parser) {
                System.out.println(rec);
            }
        }
    }

    public static final CSVFormat FORMAT = CSVFormat.Builder.create(CSVFormat.EXCEL).setCommentMarker(';').setHeader().build();
    public static final String DATA = """
            ; leading
            ; comments
            "a","b","c"
            1,2,3
            ; trailing comment
            """;
}

补充说明

常规遍历CSVRecord时只会输出数据行,表头不会作为普通记录出现在迭代结果中,因此绑定在表头前的注释不会出现在任何一条数据记录的getComment()返回值里,容易被误以为被丢弃,实际始终和表头元数据绑定存储。


内容的提问来源于stack exchange,提问作者Peter Hull

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 20:39:19