如何不覆盖文件(使用追加模式)

How to not overwrite a file(using append mode)

这是我当前的代码:

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);
            }
        }
    }
}

如何才能使其不覆盖文本文件中的当前文本?

有什么建议吗? 我做的对吗? 该程序必须向文件添加一些文本,但不能覆盖当前内容。因为现在它正在覆盖当前内容。

使用 new FileWriter(file, true); 构造函数,其中 true 用于附加到文件而不是覆盖。

FileWriter fw = new FileWriter(file); 更改为 FileWriter fw = new FileWriter(file,true);

布尔值附加模式。

来自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