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

问题描述:

我想跳过第一行并使用第二行作为标题。如何跳过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,我认为它会检测到第一行没有按” t包含任何分号并且不是记录。它没有。我试图跳过第一行(CSVFormat似乎认为是标题)与

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

但这也行不通。我能做什么? withFirstRowAsHeader和FirstRecordAsHeader有什么区别?

+1

在将fileReader提供给解析器之前,您是否尝试过读取newLine之前的内容? – Fildor

你可能想读的第一线,通过向读者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 
} 

你可以消耗的第一行,然后将它传递给CSVParser。除此之外,有一种方法#withIgnoreEmptyLines可以解决这个问题。

+0

问题是行不是空的。但是使用BufferedReader(有一个readLine方法)解决了它。 – Medusa