Android 程序重启时文件被覆盖
我正在尝试将一些数据写入文件。然而,每次我重新启动程序时,我认为它会覆盖原始文件(制作一个新文件?)这是我实例化事物的代码片段。我可以更改一些内容以使文件不会每次都被覆盖吗?类似 if file.doesExist??
try {
File root = Environment.getExternalStorageDirectory();
if(root.canWrite()){
File highscoresFile = new File(root, "names.txt");
FileWriter writer = new FileWriter(highscoresFile);
BufferedWriter out = new BufferedWriter(writer);
//out.newLine();
out.append(name);
out.close();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I am trying to write out some data to a file. However, every time I restart my program, I think it is overwriting the original file (making a new one?) Here is a snippet of code where I instantiate things. Is there something I can change so that the file doesn't get overwritten everytime? something like if file.doesExist??
try {
File root = Environment.getExternalStorageDirectory();
if(root.canWrite()){
File highscoresFile = new File(root, "names.txt");
FileWriter writer = new FileWriter(highscoresFile);
BufferedWriter out = new BufferedWriter(writer);
//out.newLine();
out.append(name);
out.close();
}
} catch (FileNotFoundException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能会覆盖该文件。您可以使用不同的构造函数将 FileWriter 附加到文件末尾。
相反,使用
末尾的布尔值告诉您是否附加到文件末尾。
You are likely overwriting the file. You can append to the end of the file with the FileWriter by using a different constructor.
Instead use
The boolean at the end tells you whether or not to append to the end of the file.