10

Is there anyway I can write to an already existing file using Filewriter

For example when the user clicks a submit button:

FileWriter writer = new FileWriter("myfile.csv");
writer.append("LastName");
writer.append(',');
writer.append("FirstName");
writer.append('/n');

writer.append(LastNameTextField.getText());
writer.append(',');
writer.append(FirstNameTextField.getText());

I want to be able to write new data into the already existing myfile.csv without having to recreate a brand new one every time

IAdapter
  • 62,595
  • 73
  • 179
  • 242
delo
  • 121
  • 1
  • 2
  • 4
  • Do you want to append (write the new data at the end of the old), or replace (write the new data over the top of the old)? I would have thought append (as did the answerers so far), but "write new data into" sounds more like replace. – CPerkins Jun 09 '10 at 11:25

2 Answers2

23

Yeah. Use the constructor like this:

FileWriter writer = new FileWriter("myfile.csv",true);
Geo
  • 93,257
  • 117
  • 344
  • 520
  • @TwilightPonyInc. It's not quite pseudocode, it is the method declaration, but yeah! The code is ALWAYS much more useful! – Radu May 21 '14 at 11:17
7
FileWriter

public FileWriter(File file,
                  boolean append)
           throws IOException

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. 
Inv3r53
  • 2,929
  • 3
  • 25
  • 37