-1

A Chapter 5 Java Question from my homework that I don't quite seem to understand:

Question:

You are opening an existing file with for output. How do you open the file without erasing it and at the same time make sure that new data written to the file is appended to the end of the file’s existing data?

If anyone could answer this question and explain the reasoning behind it so that I would understand that would be great. Thank you!

  • Just read the documentation about the modes to open a file. One mode allows you to do what the question asks for: *appended to the end of the file* –  May 06 '19 at 19:45

1 Answers1

0

Writing to a file is most often done with buffers to improve performance. If you only want to append to the file set the append flag to true (otherwise the contents will be overriden:

String textToAppend = "Happy Learning !!"; 
BufferedWriter writer = new BufferedWriter(
                         new FileWriter("c:/temp/samplefile.txt", true));   //Set true for append mode                        
writer.newLine();   //Add new line
writer.write(textToAppend);
writer.close();

This example was taken from this website. Also check other examples on this site as it provides three other ways to append to a file.

Luka Kralj
  • 446
  • 3
  • 12