0

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.

2 Answers2

5

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

Kayaman
  • 72,141
  • 5
  • 83
  • 121
0

Change FileWriter fw = new FileWriter(file); to FileWriter fw = new FileWriter(file,true);.

the boolean value append mode.

From the javadoc:

public FileWriter(String fileName, boolean append) throws IOException Constructs a FileWriter object given a file name with a boolean indicating whether or not to append the data written. Parameters:fileName - String The system-dependent filename.append - boolean if true, then data will be written to the end of the file rather than the beginning. Throws: IOException - if the named file exists but is a directory rather than a regular file, does not exist but cannot be created, or cannot be opened for any other reason

Jens
  • 67,715
  • 15
  • 98
  • 113