15

I'm using opencsv and want to write to a .csv file through multiple sessions. However every time I start a new CSVWriter the old file gets erased. Can I change the behavior of the CSVWriter to write at the end of the file instead of replacing the file?

Christian
  • 21,975
  • 33
  • 117
  • 195

4 Answers4

38

There's an option in the FileWriter instead of the CSVWriter to append at the end of the file.

This code makes it work:

mFileWriter = new FileWriter(file_path, true);
mCsvWriter = new CSVWriter(mFileWriter);
Christian
  • 21,975
  • 33
  • 117
  • 195
1

It doesn't seem possible to append to a file in opencsv (from an initial look, it looks rather simple), but if you're not restricted to opencsv you can try JExcel. To append to a file in JExcel you essentially need to create a copy then work off that, and overwrite the original. That could be similar in OpenCSV.

Edit: It seems like your only real option is to try out JExcel or read the entire file into a list, append to it, and write that out. If this is too heavy on memory, keep the stream open, read in chunks, write out chunks, then write out your appended chunk.

dekz
  • 785
  • 1
  • 7
  • 17
1

This is possible with OpenCSV, please have a look at the below example to append resultset to the existing csv file.

CSVWriter writer = new CSVWriter(new FileWriter(fileName.concat(".csv"), true), ',');

writer.writeAll(resultSet, true);

The second parameter to the FileWriter constructor is bool to open a file in append mode.

FileWriter(String fileName, boolean append) 
0

It should be possible:

FileWriter w = new FileWriter("yourfile.csv")
CSVWriter writer = new CSVWriter(w, '\t');
...
writer.flush();
CSVWriter writer2 = new CSVWriter(w, '\t');
...
writer2.flush();
w.close();

The CSV tool from the H2 database (disclaimer: I wrote it) also supports this.

Thomas Mueller
  • 44,960
  • 12
  • 100
  • 124