Search code examples
javaiooverwritefilewriter

How to not overwrite a file(using append mode)


This is my current code:

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

public class WriteToFile {
    public static void main(String[] args) {

    }

    public void Write(String content) {
        BufferedWriter bw = null;
        try {

            //Specify the file name and path here
            File file = new File("C:\\Users\\Gbruiker\\Dropbox\\Java\\Rekenen\\src\\sommen.txt");

                     /* This logic will make sure that the file 
                      * gets created if it is not present at the
                      * specified location*/
            if (!file.exists()) {
                file.createNewFile();
            }

            FileWriter fw = new FileWriter(file);
            bw = new BufferedWriter(fw);
            bw.append(content);
            bw.append("\n");
            System.out.println("File written Successfully");

        }
        catch (IOException ioe) {
            ioe.printStackTrace();
        }
        finally {
            try {
                if (bw != null)
                    bw.close();
            }
            catch (Exception ex) {
                System.out.println("Error in closing the BufferedWriter" + ex);
            }
        }
    }
}

How do I make it so that it doesn't overwrite the current text in the text file?

Any suggestions? Am I doing it the right way? The program has to add some text to a file but not overwrite to the current content. Because now it is overwriting the current content.


Solution

  • Use the new FileWriter(file, true); constructor, where true is for appending to the file rather than overwriting.