Java BufferedWriter 覆盖现有文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20860543/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 04:51:39  来源:igfitidea点击:

BufferedWriter writes over existing file

javafiletextbufferedwriter

提问by Victor Strandmoe

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());
    }
}

回答by PTwr

What you seek for is Appendmode.

你要找的是追加模式。

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

回答by La-comadreja

Whenever you type

每当你打字

new BufferedWriter(output);

or "write", you are overwriting the "output" file. Try to make sure you only declare a new BufferedWriter once throughout the course of the program, and append() to the file instead of write().

或“写入”,您正在覆盖“输出”文件。尽量确保在整个程序过程中只声明一次新的 BufferedWriter,并将 append() 附加到文件而不是 write()。

回答by Sibbo

To append the stuff at the end of the file, use the append()method of FileWriter

要将内容附加到文件末尾,请使用以下append()方法FileWriter

回答by Salih Erikci

Replace all existing content with new content.

用新内容替换所有现有内容。

new FileWriter(file);

Keep the existing content and appendthe 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();

回答by imandrewd

change the FileWrite liner to:

将 FileWrite 衬垫更改为:

output = new FileWriter(password_file, true);

which tells FileWriter to append

它告诉 FileWriter 追加

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

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