BufferedWriter writes over an existing file

I am trying to create a program that saves text in a file, and then text can be added to the file. However, every time I try to write a file, it overwrites it and writes nothing. I need him to add any information I want, AML. 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());
    }
}
+4
source share
5 answers

What you are looking for is Add .

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

Replace all existing content with new content.

new FileWriter(file);

Save existing content and add new content at 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();
+4
source

, append() FileWriter

+1
source

change liner FileWrite to:

output = new FileWriter(password_file, true);

which tells FileWriter to add

http://docs.oracle.com/javase/7/docs/api/java/io/FileWriter.html

+1
source

Whenever you type

new BufferedWriter(output);

or "write", you are overwriting the "output" file. Try to only declare a new BufferedWriter once during the entire course of the program and add () to the file instead of write ().

0
source

All Articles