Java append/add content to an existing file

Replace vs Append/Add

If you want your code to create a new file and erase previous existing file, FileWriter can simply take it place. To replace all content in an existing file, use this:

FileWriter fstream = new FileWriter(loc);

The code above will delete the existing file if it’s name is use in new file being writting.

To append/add something to an existing file, simply specify the second parameter to be true as following:

FileWriter fstream = new FileWriter(loc, true);

This will keep adding content to the existing file instead of creating a new version.

Complete Example
Here is a complete code example to do this. It is nothing particularly important but a quick code reference.

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
 
public class Main {
	public static void main(String[] args) throws IOException {
		File dir = new File(".");
		String loc = dir.getCanonicalPath() + File.separator + "Code.txt";
 
		FileWriter fstream = new FileWriter(loc, true);
		BufferedWriter out = new BufferedWriter(fstream);
 
		out.write("something");
		out.newLine();
 
		//close buffer writer
		out.close();
	}
}

Leave a Comment