Default dir to store a file that my app makes

Go To StackoverFlow.com

0

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?

2012-04-04 22:05
by user1258829


3

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.)

2012-04-04 22:08
by Ted Hopp
Okay, I didn't fully understand that. Could you please clarify that a little - user1258829 2012-04-04 22:10
@user1258829 - I added some sample cod - Ted Hopp 2012-04-04 22:15
Ads