0

Im using CSVWriter(OpenCSV) to write the data into CSV in Java.

Can any one please help me to append data to the existing data?

I tried opening the file as given below

FileWriter pw = new FileWriter("F:\\data.csv",true); 

But I could able to see the Old content is replaced and only the new data is available in the file? I want the old data along with new data.

yash
  • 2,101
  • 2
  • 23
  • 32
Alagammal P
  • 829
  • 5
  • 19
  • 43
  • Possible duplicate of [Writing at the end of a file via opencsv](http://stackoverflow.com/questions/3741564/writing-at-the-end-of-a-file-via-opencsv) – Dancrumb Feb 23 '17 at 14:26
  • This seems to have been answered here: http://stackoverflow.com/questions/3741564/writing-at-the-end-of-a-file-via-opencsv I hope this helps. – Jamason45 Feb 23 '17 at 14:26
  • I tried in the same way. But I could see only the latest row and the already existing row is not availble in the CSV – Alagammal P Feb 23 '17 at 14:34

2 Answers2

4

If you are using openCSV, then do something like this :-

CSVWriter writer = new CSVWriter(new FileWriter(csv, true));

here is full example:-

import java.io.FileWriter;

import au.com.bytecode.opencsv.CSVWriter;

public class AppendToCSVExample
{
   public static void main(String[] args) throws Exception
   {
      String csv = "data.csv";
      CSVWriter writer = new CSVWriter(new FileWriter(csv, true));

      String [] record = "3,David,Feezor,USA,40".split(",");

      writer.writeNext(record);

      writer.close();
   }
}

To append new record on existing .csv file, you have to enable append mechanism of FileWritter class(here 'true' - second argument) which enables append feature of FileWritter class.

Hope this may work for you.

aac
  • 574
  • 2
  • 6
  • 18
yash
  • 2,101
  • 2
  • 23
  • 32
0

I was using :

CSVWriter csvWriter = new CSVWriter(Files.newBufferedWriter(Paths.get(csvOutput))); When I used:

CSVWriter csvWriter = new CSVWriter(new FileWriter(csvOutput, true));

IT Worked !

rahul pareek
  • 131
  • 2
  • 2