Abhiroop
Abhiroop

Reputation: 43

Incomplete OpenCSV import

I tried importing the records from a CSV file using OpenCSV. I observed that OpenCSV was actually missing out some of the entries in the last row of my file. The code is as below. I know that I can do a writeAll operation. But i need individual rows for some other operations. The number of records are around 56000 in my file.

CSVReader reader = new CSVReader(new BufferedReader(new InputStreamReader(new FileInputStream(inputFile))));

CSVWriter writer = new CSVWriter(new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(path2+File.separator+fileName)))), ',');

List<String[]> fileContents = new ArrayList<String[]>();
fileContents = reader.readAll();
for(int i=0; i<fileContents.size(); i++){
    String[] row = fileContents.get(i);
writer.writeNext(row);

Upvotes: 0

Views: 1387

Answers (3)

chrisb89
chrisb89

Reputation: 65

Had a similar problem as described by Abhiroop when using StatefulBeanToCsv<T> beanWriter. Thanks for documenting the error with writer.close!

Since a Writer implements Closeable which extends AutoCloseable, it should be wrapped in a try-with-resources as shown below.

For me, the advantage of StatefulBeanToCsv is that it can be used with a MappingStrategy<T>.

public void exportToCsv(List<T> beans) {
    try (PrintWriter printWriter = new PrintWriter(FILE_PATH_NAME)) {
        final StatefulBeanToCsv<T> beanWriter = new StatefulBeanToCsvBuilder<T>(printWriter).build();
        beanWriter.write(beans);
    } catch (Exception e) {
        throw new IllegalStateException("export failed", e);
    }
}

Upvotes: 2

Abhiroop
Abhiroop

Reputation: 43

I figured out the error. I wasnt closing the writer. writer.close(); And the file was completely written. Don't know why it doesnt complete writing the file otherwise.

Upvotes: 1

javaist
javaist

Reputation: 43

please check if prior to the missing values, one of the values has a comma inside (i.e. "this is a csv value, with a comma inside it").

Upvotes: 0

Related Questions