BufferedWriter writes over existing file

Victor Strandmoe picture Victor Strandmoe · Dec 31, 2013 · Viewed 21.4k times · Source

I'm trying to create a program which saves text on a file and then text can be added onto the file. However, every time i try to write to the file, it overwrites it and doesn't write anything. I need it to add whatever information i want it UNDER the rest.

    FileReader input;
    BufferedReader readFile;

    FileWriter output;
    BufferedWriter writeFile;

    try {
    //  input = new FileReader(password_file);
        //readFile = new BufferedReader(input);

        output = new FileWriter(password_file);
        writeFile = new BufferedWriter(output);


        //while ((temp_user= readFile.readLine()) !=null) {
            //temp_pass = readFile.readLine();
        //}

        temp_user = save_prompt.getText();

        temp_pass = final_password;

                                        //Writes to the file
        writeFile.write(temp_user);
        writeFile.newLine();
        writeFile.write(temp_pass);

    }
    catch(IOException e) {
        System.err.println("Error: " + e.getMessage());
    }
}

Answer

PTwr picture PTwr · Dec 31, 2013

What you seek for is Append mode.

new FileWriter(file,true); // true = append, false = overwrite