File Writer overrides previous write Java

与世无争的帅哥 提交于 2020-01-11 11:52:06

问题


try {
                File file = new File(filePath+"usedcommands.txt");
                if (!file.exists()) {
                    file.createNewFile();
                }
                FileWriter fw = new FileWriter(file.getAbsoluteFile());
                BufferedWriter bw = new BufferedWriter(fw);
                bw.write(input+"\n");
                bw.close();
            } catch(Exception e) { System.out.println("can't write to usedcommands.txt..."); }

I'm writing to a txt file, but every time I run through the writing process it overrides what is already written there. How can I change my code so this part of the program doesn't override what is already there?


回答1:


Pass true as a second argument to FileWriter to turn on "append" mode.

FileWriter fw = new FileWriter(file.getAbsoluteFile(), true);



回答2:


Use this it will work

fw = new FileWriter("fileName",true);

for more details on FileWriter see this



来源:https://stackoverflow.com/questions/21537025/file-writer-overrides-previous-write-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!