-1

How can I write a new row of data to a .CSV file that already has data in it. So far my code just clears the file and doesn't actually write anything?

            BufferedReader br = null;
        BufferedWriter bw = null;
        String fileString = "patients.csv";
        String fileLine = "";

        File file = new File(fileString);
        br = new BufferedReader(new FileReader(file));
        FileWriter fw = new FileWriter(fileString);
        bw = new BufferedWriter(fw);

        while((fileLine = br.readLine()) != null){

            bw.write(fileLine);
        }


        br.close();
        bw.close();
Hovercraft Full Of Eels
  • 283,665
  • 25
  • 256
  • 373
Samuel Hornby
  • 13
  • 1
  • 6

2 Answers2

1

specify true in the constructor java FileWriter to know that the true and append be added to the end of the file if you place it does not overwrite information

FileWriter fw = new FileWriter(fileString,true);
DarkFenix
  • 706
  • 1
  • 13
  • 34
0

If you want to append to a file using FileWriter then use this Constructor

As per Javadocs

Constructs a FileWriter object given a File object. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

But, back to your code, you will only need to write new data to the FileWriter and not rewrite existing data.

Scary Wombat
  • 44,617
  • 6
  • 35
  • 64