AllanJ
AllanJ

Reputation: 147

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

I wonder why my program overwrites existing text in the textfile instead of adding a new line of text?

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

Upvotes: 0

Views: 45

Answers (1)

Andreas
Andreas

Reputation: 159106

The code overwrites the file because you didn't specify an OpenOption on the newBufferedWriter() call.

As the javadoc says:

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.

Try:

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

Or if the file must already exist, failing if it doesn't:

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

To write a new file, failing if it already exists

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

Upvotes: 1

Related Questions