shmcrae
shmcrae

Reputation: 13

Why does FileWriter overwrite the file even though I did specify it should append

This is what I have:

try{
    String filename = "Names.txt";
    FileWriter fw = new FileWriter(filename, true);
    BufferedWriter buffer = new BufferedWriter(fw);
    buffer.append("NAME: " + name + " AGE: " + age + " ID: " + id + "\n\n");

    System.out.println("We have succefully created your account.");
    buffer.close();
    start();
} catch(IOException e){
    System.err.println("ERROR");
}

It always overwrites the first line and does not go to a different one. I've used the append. This is my start method:

// this is the start method
public static void start(){
    System.out.println("1) Add Account 2) Exit");
    System.out.println("What do you want to do: ");
    stuff = input.nextInt();

    if (stuff == 1) {
        try {
            x = new Formatter("Names.txt");
        } catch (Exception e) {
            System.err.println("ERROR" );
        }
        newRecord();
    } else if(stuff == 2) {
        System.exit(0);
    } else {
        System.err.println("ERROR");
    }
}

Upvotes: 0

Views: 99

Answers (1)

Alex S. Diaz
Alex S. Diaz

Reputation: 2667

I guess is this line:

x = new Formatter("Names.txt");

From javadoc

public Formatter(String fileName) throws FileNotFoundException

Parameters:

fileName - The name of the file to use as the destination of this formatter. If the file exists then it will be truncated to zero size; otherwise, a new file will be created. The output will be written to the file and is buffered.

(I add emphasis to the part that is cleaning your file).

Upvotes: 3

Related Questions