Android - 应用程序关闭时保留文件
我正在我的 Android 应用程序中创建一个文件,如下所示:
HEADINGSTRING = new String("Android Debugging " + "\n"
"XML test Debugging");
}
public void setUpLogging(Context context){
Log.d("LOGGING", "Setting up logging.....");
try { // catches IOException below
FileOutputStream fOut = context.openFileOutput(FILE_NAME,Context.MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
osw.write(HEADINGSTRING);
/* ensure that everything is
* really written out and close */
osw.flush();
osw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
Log.d("LOGGING", "Finished logging setup.....");
}
}
我在应用程序运行期间写入该文件,如下所示:
public void addToLog(File file, String text) throws IOException {
BufferedWriter bw = new BufferedWriter (new FileWriter(file, true));
bw.write ("\n" + text);
bw.newLine();
bw.flush();
bw.close();
}
这工作正常,但是当我的应用程序关闭时,文件会被删除,当应用程序再次运行时,我的所有信息都会被删除。写给它的已经消失了。
如何确保即使在应用程序关闭后文件仍然存在?
更新:
我已将 MODE_PRIVATE 更改为 MODE_APPEND,问题已解决,感谢 Skirmish。
I am creating a file in my Android application as follows:
HEADINGSTRING = new String("Android Debugging " + "\n"
"XML test Debugging");
}
public void setUpLogging(Context context){
Log.d("LOGGING", "Setting up logging.....");
try { // catches IOException below
FileOutputStream fOut = context.openFileOutput(FILE_NAME,Context.MODE_APPEND);
OutputStreamWriter osw = new OutputStreamWriter(fOut);
// Write the string to the file
osw.write(HEADINGSTRING);
/* ensure that everything is
* really written out and close */
osw.flush();
osw.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
finally{
Log.d("LOGGING", "Finished logging setup.....");
}
}
And I write to the file during the running of the app as follows:
public void addToLog(File file, String text) throws IOException {
BufferedWriter bw = new BufferedWriter (new FileWriter(file, true));
bw.write ("\n" + text);
bw.newLine();
bw.flush();
bw.close();
}
This works fine but when my app closes the file gets deleted and when the app is run again all the information I wrote to it is gone.
How can I make sure the file persists even after closure of the app?
Update:
I have changed MODE_PRIVATE to MODE_APPEND and the problem is fixed, thanks Skirmish.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可能需要检查 http://developer .android.com/reference/android/content/Context.html#openFileOutput(java.lang.String, int) 特别是关于 MODE_APPEND 的部分,而不是每次应用程序启动时清除所有内容。
You might want to check http://developer.android.com/reference/android/content/Context.html#openFileOutput(java.lang.String, int) especially the part about MODE_APPEND rather than clearing everything out every time the app starts.