简体   繁体   中英

Skip first line using Open CSV reader

Here is the line i am using currently

File booleanTopicFile;
// booleanTopicFile is csv file uploaded from form
CSVReader csvReader = new CSVReader(new InputStreamReader(new FileInputStream(booleanTopicFile), "UTF-8"));

Want to skip the first line of the csv which contains headings. I dont want to use any separator as except the default one comma(,) which is already available in default constructor. In parameterized constructor there is a option to skip no. of lines but how to deal with the 2nd and 3rd param of the constructor.

CSVReader csvReader = new CSVReader(new InputStreamReader(Reader reader, char c, char c1, int index);

-- Thanks

CSVReader类的此构造方法在读取文件时将跳过csv的第一行。

CSVReader reader = new CSVReader(new FileReader(file), ',', '\'', 1);

I found this question and response helpful, I'd like to expand on Christophe Roussy's comment . In the latest opencsv (2.3 as of this writing) The actual line of code is:

new CSVReader( new StringReader(csvText), CSVParser.DEFAULT_SEPARATOR,
               CSVParser.DEFAULT_QUOTE_CHARACTER, 1);

Note it uses CSVParser instead of CSVReader.

At least since version 3.8 you can use the CSVReaderBuilder and set it to skip the first line.

Example:

CSVReader reader = new CSVReaderBuilder(inputStreamReader)
                .withFieldAsNull(CSVReaderNullFieldIndicator.EMPTY_SEPARATORS)
                // Skip the header
                .withSkipLines(1)
                .build();

最新版本的opencsv版本使用-

CSVReader csvReader = new CSVReaderBuilder(new FileReader("book.csv")).withSkipLines(1).build()

You can also use withFilter :

watFileCsvBeans = new CsvToBeanBuilder<ClassType>(isr)
  .withType(ClassType.class)
  .withIgnoreLeadingWhiteSpace(true)
  // CsvToBeanFilter with a custom allowLine implementation
  .withFilter(line -> !line[0].equals("skipme"))
  .build()
  .parse();
watFileCsvBeans = new CsvToBeanBuilder<ClassType>(isr)
  .withType(ClassType.class)
  .withIgnoreLeadingWhiteSpace(true)
  // CsvToBeanFilter with a custom allowLine implementation
  .withFilter(line -> !line[0].equals("skipme"))
  .build()
  .parse(); 

It's useful in my case. Instead, "withSkipLines" is not working for me. opencsv version: 5.5.2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM