Save a file on internal storage

Your app's internal storage directory is specified by your app's package name in a special location of the Android file system that can be accessed with the following APIs.

Query free space

If you know ahead of time how much data you're saving, you can find out whether sufficient space is available without causing an IOException by calling getFreeSpace() or getTotalSpace(). These methods provide the current available space and the total space in the storage volume, respectively. This information is also useful to avoid filling the storage volume above a certain threshold.

However, the system doesn't guarantee that you can write as many bytes as are indicated by getFreeSpace(). If the number returned is a few MB more than the size of the data you want to save, or if the file system is less than 90% full, then it's OK to proceed. Otherwise, you probably shouldn't write to storage.

Write a file

When saving a file to internal storage, you can acquire the appropriate directory as a File object by calling one of the following methods:

getFilesDir()
Returns a File representing an internal directory for your app.
getCacheDir()

Returns a File representing an internal directory for your app's temporary cache files. Be sure to delete each file once it's no longer needed and implement a reasonable size limit for the amount of memory you use at any given time, such as 1 MB.

Caution: If the system runs low on storage, it may delete your cache files without warning.

To create a new file in one of these directories, you can use the File() constructor, passing the File provided by one of the above methods that specifies your internal storage directory. For example:

Kotlin

val file = File(context.filesDir, filename)

Java

File file = new File(context.getFilesDir(), filename);

Alternatively, you can call openFileOutput() to get a FileOutputStream that writes to a file in your internal directory. For example, here's how to write some text to a file:

Kotlin

val filename = "myfile"
val fileContents = "Hello world!"
context.openFileOutput(filename, Context.MODE_PRIVATE).use {
        it.write(fileContents.toByteArray())
}

Java

String filename = "myfile";
String fileContents = "Hello world!";
FileOutputStream outputStream;

try {
    outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
    outputStream.write(fileContents.getBytes());
    outputStream.close();
} catch (Exception e) {
    e.printStackTrace();
}

Notice that the openFileOutput() method requires a file mode parameter. Passing MODE_PRIVATE makes it private to your app. The other mode options, MODE_WORLD_READABLE and MODE_WORLD_WRITEABLE, have been deprecated since API level 17. Starting with Android 7.0 (API level 24), Android throws a SecurityException if you use them. If your app needs to share private files with other apps, you should instead use a FileProvider with the FLAG_GRANT_READ_URI_PERMISSION attribute. For more information, see Sharing Files.

On Android 6.0 (API level 23) and lower, other apps can read your internal files if you set the file mode to be world readable. However, the other app must know your app package name and file names. Other apps cannot browse your internal directories and don't have read or write access unless you explicitly set the files to be readable or writable. So as long as you use MODE_PRIVATE for your files on the internal storage, they are never accessible to other apps.

Write a cache file

If you instead need to cache some files, you should use createTempFile(). For example, the following method extracts the file name from a URL object and creates a file with that name in your app's internal cache directory:

Kotlin

private fun getTempFile(context: Context, url: String): File? =
        Uri.parse(url)?.lastPathSegment?.let { filename ->
            File.createTempFile(filename, null, context.cacheDir)
        }

Java

private File getTempFile(Context context, String url) {
    File file;
    try {
        String fileName = Uri.parse(url).getLastPathSegment();
        file = File.createTempFile(fileName, null, context.getCacheDir());
    } catch (IOException e) {
        // Error while creating file
    }
    return file;
}

Files created with createTempFile() are placed in a cache directory that's private to your app. You should regularly delete the files you no longer need.

Open an existing file

To read an existing file, call openFileInput(name), passing the name of the file.

You can get an array of all your app's file names by calling fileList().

Open a directory

You can open a directory on the internal file system with the following methods:

getFilesDir()
Returns a File object representing the directory on the file system that's uniquely associated with your app.
getDir(name, mode)
Creates a new directory (or opens an existing directory) within your app's unique file system directory. This new directory appears inside the directory provided by getFilesDir().
getCacheDir()
Returns a File object representing the cache directory on the file system that's uniquely associated with your app. This directory is meant for temporary files, and it should be cleaned up regularly. The system may delete files there if it runs low on disk space, so make sure you check for the existence of your cache files before reading them.

To create a new file in one of these directories, you can use the File() constructor, passing the File object provided by one of the above methods that specifies your internal storage directory. For example:

Kotlin

val directory = context.filesDir
val file = File(directory, filename)

Java

File directory = context.getFilesDir();
File file = new File(directory, filename);

Delete a file

You should always delete files that your app no longer need. The most straightforward way to delete a file is to call delete() on the File object:

Kotlin

myFile.delete()

Java

myFile.delete();

If the file is saved on internal storage, you can also ask the Context to locate and delete a file by calling deleteFile():

Kotlin

myContext.deleteFile(fileName)

Java

myContext.deleteFile(fileName);

Note: When the user uninstalls your app, the Android system deletes the following:

  • All files you saved on internal storage.
  • All files you saved external storage using getExternalFilesDir().

However, you should manually delete all cached files created with getCacheDir() on a regular basis and also regularly delete other files you no longer need.

Additional resources

For more information about saving files to the device's storage, consult the following resources.

Codelabs