java – BufferedWriter写入现有文件

参见英文答案 > How to append text to an existing file in Java                                    30个
>            Trouble with filewriter overwriting files instead of appending to the end                                    3个
我正在尝试创建一个程序,将文本保存在文件上,然后将文本添加到文件中.但是,每次我尝试写入文件时,它都会覆盖它并且不会写任何内容.我需要它来添加我想要的任何信息.

    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());
    }
}
最佳答案
你寻求的是追加模式.

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

转载注明原文:java – BufferedWriter写入现有文件 - 代码日志