Reputation: 73
A question, I'm making a app that will store a textfile (.txt) with highscore data. I've made a file with this line from my highscores activity:
File highscoreList = new File("highscores.txt");
Where will it be placed? In the same dir as the highscores.java file? Or, how should I specify a dir that will put the textfile in the same folder as highscores.java?
Upvotes: 0
Views: 456
Reputation: 234795
You should access your files using the Context methods openFileInput
and openFileOutput
. You can determine where they are actually stored using getFileStreamPath
. (The directory they go in can be obtained with getFilesDir
.) The advantage of using this method is that the files will be private to your application and will be removed automatically if your app is uninstalled.
In your activity, you can create your File
with:
File highscoreList = getFileStreamPath("highscores.txt");
If all you want to do is write to it:
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);
}
}
}
Similarly, for reading you can use:
FileInputStream input = openFileInput("highscores.txt");
If you are trying to access your file from outside an Activity
subclass, you'll need a Context
. (In a View
, for instance, you can use getContext()
. For a helper class, you'll need to pass in your Activity
instance or some other Context
object.)
Upvotes: 3