微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何跳过Java中csv的第一行?

我想跳过第一行并使用第二行作为标题.

我正在使用apache commons csv中的类来处理CSV文件.

CSV文件标题位于第二行,而不是第一行(包含坐标).

我的代码看起来像这样:

static void processFile(final File file) {
    FileReader filereader = new FileReader(file);
    final CSVFormat format = CSVFormat.DEFAULT.withDelimiter(';');
    CSVParser parser = new CSVParser(filereader,format);
    final List<CSVRecord> records = parser.getRecords();
    //stuff
}

我天真地想,

CSVFormat format = CSVFormat.DEFAULT.withFirstRecordAsHeader().withDelimiter(;)

解决问题,因为它与withFirstRowAsHeader不同,我认为它会检测到第一行不包含任何分号而不是记录.它没有.我试图跳过第一行(CSVFormat似乎认为是标题)

CSVFormat format = CSVFormat.DEFAULT.withSkipHeaderRecord().withFirstRecordAsHeader().withDelimiter(;);

但这也行不通.我能做什么? withFirstRowAsHeader和withFirstRecordAsHeader之间的区别是什么?

解决方法

在将阅读器传递给CSVParser之前,您可能需要阅读第一行:
static void processFile(final File file) {
    FileReader filereader = new FileReader(file);
    BufferedReader bufferedReader = new BufferedReader(filereader);
    bufferedReader.readLine();// try-catch omitted
    final CSVFormat format = CSVFormat.DEFAULT.withDelimiter(';');
    CSVParser parser = new CSVParser(bufferedReader,format);
    final List<CSVRecord> records = parser.getRecords();
    //stuff
}

原文地址:https://www.jb51.cc/java/240022.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐