Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

BufferedWriter writes over existing file [duplicate]

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());
    }
}
like image 470
Victor Strandmoe Avatar asked Dec 31 '13 16:12

Victor Strandmoe


2 Answers

What you seek for is Append mode.

new FileWriter(file,true); // true = append, false = overwrite
like image 175
PTwr Avatar answered Sep 28 '22 03:09

PTwr


Replace all existing content with new content.

new FileWriter(file);

Keep the existing content and append the new content in the end of the file.

new FileWriter(file,true);

Example:

    FileWriter fileWritter = new FileWriter(file.getName(),true);
        BufferedWriter bufferWritter = new BufferedWriter(fileWritter);
        bufferWritter.write(data);
        bufferWritter.close();
like image 37
Salih Erikci Avatar answered Sep 28 '22 03:09

Salih Erikci