Click here to Skip to main content
15,943,294 members
Articles / Mobile Apps / Android

Saving Data to a File in Your Android Application

Rate me:
Please Sign up or sign in to vote.
4.35/5 (9 votes)
2 Jun 2014CPOL6 min read 72.6K   16   8
How to save data to a file in your Android application

This is the second post in my series about storage in Android applications. The other post is available here:

This post is about saving to a file from an Android application, which is the easiest way to store data. There are many situations where you may need to save a file: you may want to use an existing file format to create files that can be opened by the user in another application or the data is simple enough that it can be represented by a text file or a format like XML or YAML. For complex data, a database may be a better option, since accessing and parsing a large file can be slow and there are no integrity checks unless you code them by hand. On the other hand, there is less overhead and it easier to work with files than debugging with the data in a database. Depending on how the user will interact (or not) with your files, you will need to decide first which kind of storage to use.

Internal Storage

Each application has its own private internal storage to save files. This is the kind of storage to use if the user shouldn’t be able to modify the file from outside your application, and if other application shouldn’t be able to access those files. Since the internal storage is private to your application, the files will be deleted if your application is uninstalled. The internal storage is also where your application is installed by default, so your files will always be available. On some older or cheaper devices, the internal storage is quite limited, so you need to be careful about the size of the data you save if you need to support those devices.

You should never hardcode the path to the storage directories, since the directory may changes depending on the version of the Android OS used. Also, Android 4.4 introduces the concept of multiple users: in that case, the internal and external storage depend on the user logged in and the files of the other users will be invisible. Here are some of the methods used to get the paths to the internal storage:

  • android.content.Context.getFilesDir(): returns a object representing the root directory of the internal storage for your application from the current context.
  • android.content.Context.getDir(String name, Context.MODE_PRIVATE): returns a object representing the directory name in the internal storage, creating the directory if it does not exists. The second parameter can also be used to set the directory to MODE_WORLD_READABLE or MODE_WORLD_WRITABLE so it is visible by all the other applications, but this is is risky security-wise and was deprecated in API level 17 (Android 4.2).
  • android.content.Context.getCacheDir(): returns a object representing the internal cache directory for the application. This is mean for small files (the documentation suggests no more that 1MB total) that can be deleted at any time when the system needs more storage. There is no guarantee that the cache will be cleared, so you must also clear those files manually when they are not needed anymore.

As you can see, the files are represented by the File object from the namepace: there is no file object specific to the Android SDK and the standard Java APIs for reading and writing files are used. Also, there is no specific application permission to set in the Android manifest to use the internal storage since it is already private to the application.

External Storage

In addition of the internal storage, there is an external storage space shared by all the applications that is kept when your application is uninstalled. This is the storage that is shown when using a file explorer application and when the device is plugged in your computer. It may be implemented as a SD card that can be removed or as a partition of the built-in storage in the device, so your application should be able to work even if the card is removed or changed. To check the current state of the external storage, you can call the getExternalStorageState() method.

On device with many users (starting with Android 4.4), the external storage is specific to the current user and files for other users can’t be accessed. Also, there may be more than one external storage if the device has a built-in external storage which is a partition on the internal memory and a SD card: in that case, the built-in storage is the primary external storage. Reading files from the external storage requires the READ_EXTERNAL_STORAGE permission and writing or reading files requires the WRITE_EXTERNAL_STORAGE permission.

Here are the methods you should use to call to get the directories of the primary external storage:

  • android.os.Environment.getExternalStorageDirectory(): returns a object representing the root directory of the primary external storage of the device that is shared by all applications.
  • android.os.Environment.getExternalStoragePublicDirectory(): returns a object representing a public directory for files of a particular type on the primary external storage of the device. For example, you can get the path to the public music directory by calling Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC) or the public pictures directory by calling Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).
  • android.content.Context.getExternalFilesDir(): returns a representing the root directory of the primary external storage specific to your application, which is under the directory returned by getExternalStorageDirectory(). Unlike the other directories of the external storage, the files you store in that folder will be deleted when your application is uninstalled. So, if you need to store files that are only needed by your application you should use this folder. Also, there is no specific permission needed for the application to read or write to its own external storage starting with Android 4.4, but with older versions your application needs the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE permission.
  • android.content.Context.getExternalFilesDirs(): returns an array of representing the root directories of all the external storage directories that can be used by your application with the primary external storage as the first directory in the array. All those directories work the same as the primary storage returned by the getExternalFilesDir() method. If the device has a built-in storage as the primary external storage and a SD card as a secondary external storage, this is the only way to get the path to the SD card. This method was introduced in Android 4.4, before that it was impossible to get the path to the secondary storage.
  • android.content.Context.getExternalCacheDir(): returns a object representing the cache of the application on the primary external storage. This cache is not visible to the user and is deleted when the application is uninstalled. There is no mechanism in the Android SDK to delete files in the cache directory, so you need to manage your cache to keep it to a reasonable maximum size. Starting with Android 4.4, the application does not need permission to access its own cache, but with older versions your application needs the READ_EXTERNAL_STORAGE or WRITE_EXTERNAL_STORAGE permission.

Example Code to Save to a File

To save a file, you need to get the path to the storage you want to use which is used the same way regardless of the type of storage used since all the methods returns a object representing the directory to use. Here is an example of using the external storage to save a text file from an Activity:

                            // Creates a trace file in the primary external storage space of the 
                            // current application.
                            // If the file does not exists, it is created.
   File traceFile = new File(((Context)this).getExternalFilesDir(null), "TraceFile.txt");
   if (!traceFile.exists())
                            // Adds a line to the trace file
   BufferedWriter writer = new BufferedWriter(new FileWriter(traceFile, true /*append*/));
   writer.write("This is a test trace file.");
                           // Refresh the data so it can seen when the device is plugged in a
                           // computer. You may have to unplug and replug the device to see the 
                           // latest changes. This is not necessary if the user should not modify
                           // the files.
                                     new String[] { traceFile.toString() },
catch (IOException e)
    Log.e("com.cindypotvin.FileTest", "Unable to write to the TraceFile.txt file.");


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Written By
Canada Canada
Cindy Potvin is a software developer based in the Montreal area. At her day job, she creates web applications using the ASP.NET MVC framework and mobile applications using the Android SDK.

Comments and Discussions

Questionstoring the multiple data in external device Pin
Member 129869589-Mar-17 23:50
Member 129869589-Mar-17 23:50 
QuestionVery nnice Pin
Peltier Cooler18-Sep-14 15:16
professionalPeltier Cooler18-Sep-14 15:16 
AnswerRe: Very nnice Pin
Cindy Potvin20-Sep-14 5:43
Cindy Potvin20-Sep-14 5:43 
GeneralRe: Very nnice Pin
Peltier Cooler22-Sep-14 6:07
professionalPeltier Cooler22-Sep-14 6:07 
GeneralRe: Very nnice Pin
Cindy Potvin22-Sep-14 15:09
Cindy Potvin22-Sep-14 15:09 
Questiongood Pin
Readiprint3-Jun-14 2:02
Readiprint3-Jun-14 2:02 
SuggestionTypo - no biggie Pin
Peter_in_27801-Jun-14 20:32
professionalPeter_in_27801-Jun-14 20:32 
GeneralRe: Typo - no biggie Pin
Cindy Potvin2-Jun-14 0:55
Cindy Potvin2-Jun-14 0:55 
GeneralMy vote of 4 Pin
Sunasara Imdadhusen28-May-14 3:14
professionalSunasara Imdadhusen28-May-14 3:14 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.