Search code examples
javaopencsv

Reset the iterator of CsvToBean from opencsv java package


I am using opencsv package to read a .csv file.

I would like to read multiple times the same .csv file without re-opening the file and without re-creating the Reader object.

I am using the reset() method of the Reader object to reset the reading cursor at the start of the file.

Here is the code i am using :

reader = Files.newBufferedReader(Paths.get(path));

csvToBean = new CsvToBeanBuilder(reader)
            .withType(MyBean.class)
            .withIgnoreLeadingWhiteSpace(true)
            .build();

it = csvToBean.iterator();

while (it.hasNext()) {
    MyBean csvData = it.next();

    // blabla ...
}


reader.reset();

// I do not want to recreate the csvToBean object, i've done it to investigate error
// I got the same result zhe i do not recreate the object
csvToBean = new CsvToBeanBuilder(reader)
            .withType(MyBean.class)
            .withIgnoreLeadingWhiteSpace(true)
            .build();

it = csvToBean.iterator(); // <<<<<< FAILING HERE

Unfortunately, when i want to access the Iterator of the CsvToBean<T> object, i am encoutering the following error :

java.lang.RuntimeException: Error capturing CSV header! at

com.opencsv.bean.CsvToBean.prepareToReadInput(CsvToBean.java:468)
at com.opencsv.bean.CsvToBean.iterator(CsvToBean.java:487)
at com.myproject.test.main(test.java:37)

Caused by: java.lang.NullPointerException at

com.opencsv.bean.HeaderColumnNameMappingStrategy.captureHeader(HeaderColumnNameMappingStrategy.java:117)
at com.opencsv.bean.CsvToBean.prepareToReadInput(CsvToBean.java:466)
... 2 more

How to reset the reader of the reader properly with the opencsv package ?


Solution

  • Using a FileInputStream passed to the BufferedReader object, and resetting the FileInputStream cursor to 0 solved my problem.

    I was mixing FileInputStream that provides IO cursor manipulation with BufferedReader which provides tools on how much bytes will be load from the FileInputStream. My bad ...

    fIn = new FileInputStream(Paths.get(path).toString());
    
    reader = new BufferedReader(new InputStreamReader(fIn));
    
    csvToBean = new CsvToBeanBuilder(reader)
            .withType(MyBean.class)
            .withIgnoreLeadingWhiteSpace(true)
            .build();
    
    it = csvToBean.iterator();
    
    while (it.hasNext()) {
        MyBean csvData = it.next();
    
        // blabla ...
    }
    
    fIn.getChannel().position(0);
    
    reader = new BufferedReader(new InputStreamReader(fIn));
    
    csvToBean = new CsvToBeanBuilder(reader)
            .withType(MyBean.class)
            .withIgnoreLeadingWhiteSpace(true)
            .build();
    
    it = csvToBean.iterator(); // <<<<<< NOT FAILING HERE