您应该使用Context方法openFileInput
和openFileOutput
来访问您的文件。您可以使用getFileStreamPath
确定它们实际存储的位置。 (他们的目录可以通过getFilesDir
获得。)使用这种方法的优点是这些文件对于您的应用程序是私人的,如果您的应用程序被卸载,这些文件将被自动删除。
在您的活动,您可以创建File
有:
File highscoreList = getFileStreamPath("highscores.txt");
如果你想要做的就是写它:
FileOutputStream output = null;
try {
output = openFileOutput("highscores.txt", MODE_PRIVATE);
// write to file
} finally {
if (output != null) {
try { output.close(); }
catch (IOException e) {
Log.w(LOG_TAG, "Error closing file!", e);
}
}
}
同样,对于阅读你可以使用:
FileInputStream input = openFileInput("highscores.txt");
如果您尝试从Activity
子类以外访问您的文件,需要一个Context
。 (在View
,例如,你可以使用getContext()
。对于一个辅助类,你需要在你的Activity
实例或其他一些Context
对象传递。)
好吧,我没有完全理解这一点。你能否澄清一点? – user1258829 2012-04-04 22:10:23
@ user1258829 - 我添加了一些示例代码 – 2012-04-04 22:15:49