2017-08-24 6 views
3

最初の行をスキップし、2番目の行をヘッダーとして使用したいとします。Javaでcsvの最初の行をスキップする方法はありますか?

私は、apache commons csvのクラスを使用してCSVファイルを処理しています。

CSVファイルのヘッダーは、最初の(座標を含む)2番目の行にはありません。

私のコードは次のようになります。

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 
} 

私は単純に考えて、それはwithFirstRowAsHeader異なるだと私はそれが最初の行は」doesnのことを検出するだろうと思ったよう

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

は、問題を解決しますセミコロンを含み、レコードではありません。それはしません。私は

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

で(CSVFormatが考えているようだというヘッダがある)最初の行をスキップしようとしたが、それはまた、動作しません。私に何ができる? withFirstRowAsHeaderとwithFirstRecordAsHeaderの違いは何ですか?

+1

fileReaderをパーサに渡す前に、newLineまで読んでみましたか? – Fildor

答えて

5

あなたは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 
} 
0

あなたが最初の行を消費して、CSVParserにそれを渡すことができます。それ以外には、問題を解決する方法#withIgnoreEmptyLinesがあります。

+0

問題は、行が空ではないことです。しかし、(readLineメソッドを持つ)BufferedReaderを使って解決しました。 – Medusa

関連する問題