Java,如何写入或添加而不是覆盖文本文件?

Java, how to write or add instead of overwriting a textfile?

我想知道为什么我的程序会覆盖文本文件中的现有文本而不是添加新的文本行?

public class WriteToFile {

    public void registerTrainingSession(Customer customer) {

        Path outFilePath = Paths.get("C:\Users\Allan\Documents\Nackademin\OOP\Inlämningsuppgift2\visits.txt");


        try (BufferedWriter save = Files.newBufferedWriter(outFilePath)) {

            String trainingSession = String.format("Member: %s %s\nPersonalnumber: %s\nTraining session date: %s\n", customer.getFirstName(),
                    customer.getLastName(), customer.getPersonalNumber(), LocalDate.now());


            save.write(trainingSession);
            save.flush();

        }
        catch (NullPointerException e) {
            JOptionPane.showMessageDialog(null, "Customer info is missing!");
        }
        catch (IOException e) {
            JOptionPane.showMessageDialog(null, "File could not be created.");
        }
    }
}

代码覆盖文件,因为您没有指定 OpenOption on the newBufferedWriter() 调用。

正如 javadoc 所说:

If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0 if it exists.

尝试:

 Files.newBufferedWriter(outFilePath, StandardOpenOption.CREATE,
                                      StandardOpenOption.APPEND,
                                      StandardOpenOption.WRITE)

或者如果文件必须已经存在,如果不存在则失败:

 Files.newBufferedWriter(outFilePath, StandardOpenOption.APPEND,
                                      StandardOpenOption.WRITE)

写入一个新文件,如果它已经存在则失败

 Files.newBufferedWriter(outFilePath, StandardOpenOption.CREATE_NEW,
                                      StandardOpenOption.WRITE)