Home | History | Annotate | Download | only in data-storage
      1 page.title=Saving Files
      2 page.tags=data storage
      3 helpoutsWidget=true
      4 
      5 trainingnavtop=true
      6 
      7 @jd:body
      8 
      9 
     10 <div id="tb-wrapper">
     11 <div id="tb">
     12 
     13 <h2>This lesson teaches you to</h2>
     14 <ol>
     15   <li><a href="#InternalVsExternalStorage">Choose Internal or External Storage</a></li>
     16   <li><a href="#GetWritePermission">Obtain Permissions for External Storage</a></li>
     17   <li><a href="#WriteInternalStorage">Save a File on Internal Storage</a></li>
     18   <li><a href="#WriteExternalStorage">Save a File on External Storage</a></li>
     19   <li><a href="#GetFreeSpace">Query Free Space</a></li>
     20   <li><a href="#DeleteFile">Delete a File</a></li>
     21 </ol>
     22 
     23 <h2>You should also read</h2>
     24 <ul>
     25   <li><a href="{@docRoot}guide/topics/data/data-storage.html#filesInternal">Using the Internal
     26 Storage</a></li>
     27   <li><a href="{@docRoot}guide/topics/data/data-storage.html#filesExternal">Using the External
     28 Storage</a></li>
     29 </ul>
     30 
     31 </div>
     32 </div>
     33 
     34 <p>Android uses a file system that's
     35 similar to disk-based file systems on other platforms. This lesson describes
     36 how to work with the Android file system to read and write files with the {@link java.io.File}
     37 APIs.</p>
     38 
     39 <p>A {@link java.io.File} object is suited to reading or writing large amounts of data in
     40 start-to-finish order without skipping around. For example, it's good for image files or
     41 anything exchanged over a network.</p>
     42 
     43 <p>This lesson shows how to perform basic file-related tasks in your app.
     44 The lesson assumes that you are familiar with the basics of the Linux file system and the
     45 standard file input/output APIs in {@link java.io}.</p>
     46 
     47 
     48 <h2 id="InternalVsExternalStorage">Choose Internal or External Storage</h2>
     49 
     50 <p>All Android devices have two file storage areas: "internal" and "external" storage.  These names
     51 come from the early days of Android, when most devices offered built-in non-volatile memory
     52 (internal storage), plus a removable storage medium such as a micro SD card (external storage).
     53 Some devices divide the permanent storage space into "internal" and "external" partitions, so even
     54 without a removable storage medium, there are always two storage spaces and
     55 the API behavior is the same whether the external storage is removable or not.
     56 The following lists summarize the facts about each storage space.</p>
     57 
     58 <div class="col-5" style="margin-left:0">
     59 <p><b>Internal storage:</b></p>
     60 <ul>
     61 <li>It's always available.</li>
     62 <li>Files saved here are accessible by only your app.</li>
     63 <li>When the user uninstalls your app, the system removes all your app's files from
     64 internal storage.</li>
     65 </ul>
     66 <p>Internal storage is best when you want to be sure that neither the user nor other apps can
     67 access your files.</p>
     68 </div>
     69 
     70 <div class="col-7" style="margin-right:0">
     71 <p><b>External storage:</b></p>
     72 <ul>
     73 <li>It's not always available, because the user can mount the external storage as USB storage
     74 and in some cases remove it from the device.</li>
     75 <li>It's world-readable, so
     76 files saved here may be read outside of your control.</li>
     77 <li>When the user uninstalls your app, the system removes your app's files from here
     78 only if you save them in the directory from {@link android.content.Context#getExternalFilesDir
     79 getExternalFilesDir()}.</li>
     80 </ul>
     81 <p>External storage is the best
     82 place for files that don't require access restrictions and for files that you want to share
     83 with other apps or allow the user to access with a computer.</p>
     84 </div>
     85 
     86 <p class="note">
     87 <strong>Note:</strong> Before Android N, internal files could be made accessible to other
     88 apps by means of relaxing file system permissions. This is no longer the case. If you wish
     89 to make the content of a private file accessible to other apps, your app may use the
     90 {@link android.support.v4.content.FileProvider}. See <a
     91 href="{@docRoot}training/secure-file-sharing/index.html">Sharing Files</a>.</p>
     92 
     93 <p class="note" style="clear:both">
     94 <strong>Tip:</strong> Although apps are installed onto the internal storage by
     95 default, you can specify the <a
     96 href="{@docRoot}guide/topics/manifest/manifest-element.html#install">{@code
     97 android:installLocation}</a> attribute in your manifest so your app may
     98 be installed on external storage. Users appreciate this option when the APK size is very large and
     99 they have an external storage space that's larger than the internal storage. For more
    100 information, see <a
    101 href="{@docRoot}guide/topics/data/install-location.html">App Install Location</a>.</p>
    102 
    103 
    104 <h2 id="GetWritePermission">Obtain Permissions for External Storage</h2>
    105 
    106 <p>To write to the external storage, you must request the
    107   {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE} permission in your <a
    108 href="{@docRoot}guide/topics/manifest/manifest-intro.html">manifest file</a>:</p>
    109 
    110 <pre>
    111 &lt;manifest ...>
    112     &lt;uses-permission android:name=&quot;android.permission.WRITE_EXTERNAL_STORAGE&quot; /&gt;
    113     ...
    114 &lt;/manifest>
    115 </pre>
    116 
    117 <div class="caution"><p><strong>Caution:</strong>
    118 Currently, all apps have the ability to read the external storage
    119 without a special permission. However, this will change in a future release. If your app needs
    120 to read the external storage (but not write to it), then you will need to declare the {@link
    121 android.Manifest.permission#READ_EXTERNAL_STORAGE} permission. To ensure that your app continues
    122 to work as expected, you should declare this permission now, before the change takes effect.</p>
    123 <pre>
    124 &lt;manifest ...>
    125     &lt;uses-permission android:name=&quot;android.permission.READ_EXTERNAL_STORAGE&quot; /&gt;
    126     ...
    127 &lt;/manifest>
    128 </pre>
    129 <p>However, if your app uses the {@link android.Manifest.permission#WRITE_EXTERNAL_STORAGE}
    130 permission, then it implicitly has permission to read the external storage as well.</p>
    131 </div>
    132 
    133 <p>You dont need any permissions to save files on the internal
    134 storage. Your application always has permission to read and
    135 write files in its internal storage directory.</p>
    136 
    137 
    138 
    139 
    140 
    141 <h2 id="WriteInternalStorage">Save a File on Internal Storage</h2>
    142 
    143 <p>When saving a file to internal storage, you can acquire the appropriate directory as a
    144 {@link java.io.File} by calling one of two methods:</p>
    145 
    146 <dl>
    147   <dt>{@link android.content.Context#getFilesDir}</dt>
    148   <dd>Returns a {@link java.io.File} representing an internal directory for your app.</dd>
    149   <dt>{@link android.content.Context#getCacheDir}</dt>
    150   <dd>Returns a {@link java.io.File} representing an internal directory for your app's temporary
    151 cache files. Be sure to delete each file once it is no
    152 longer needed and implement a reasonable size limit for the amount of memory you use at any given
    153 time, such as 1MB. If the system begins running low on storage, it may delete your cache files
    154 without warning.</dd>
    155 </dl>
    156 
    157 <p>To create a new file in one of these directories, you can use the {@link
    158 java.io.File#File(File,String) File()} constructor, passing the {@link java.io.File} provided by one
    159 of the above methods that specifies your internal storage directory. For example:</p>
    160 
    161 <pre>
    162 File file = new File(context.getFilesDir(), filename);
    163 </pre>
    164 
    165 <p>Alternatively, you can call {@link
    166 android.content.Context#openFileOutput openFileOutput()} to get a {@link java.io.FileOutputStream}
    167 that writes to a file in your internal directory. For example, here's
    168 how to write some text to a file:</p>
    169 
    170 <pre>
    171 String filename = "myfile";
    172 String string = "Hello world!";
    173 FileOutputStream outputStream;
    174 
    175 try {
    176   outputStream = openFileOutput(filename, Context.MODE_PRIVATE);
    177   outputStream.write(string.getBytes());
    178   outputStream.close();
    179 } catch (Exception e) {
    180   e.printStackTrace();
    181 }
    182 </pre>
    183 
    184 <p>Or, if you need to cache some files, you should instead use {@link
    185 java.io.File#createTempFile createTempFile()}. For example, the following method extracts the
    186 file name from a {@link java.net.URL} and creates a file with that name
    187 in your app's internal cache directory:</p>
    188 
    189 <pre>
    190 public File getTempFile(Context context, String url) {
    191     File file;
    192     try {
    193         String fileName = Uri.parse(url).getLastPathSegment();
    194         file = File.createTempFile(fileName, null, context.getCacheDir());
    195     catch (IOException e) {
    196         // Error while creating file
    197     }
    198     return file;
    199 }
    200 </pre>
    201 
    202 <p class="note"><strong>Note:</strong>
    203 Your app's internal storage directory is specified
    204 by your app's package name in a special location of the Android file system.
    205 Technically, another app can read your internal files if you set
    206 the file mode to be readable. However, the other app would also need to know your app package
    207 name and file names. Other apps cannot browse your internal directories and do not have
    208 read or write access unless you explicitly set the files to be readable or writable. So as long
    209 as you use {@link android.content.Context#MODE_PRIVATE} for your files on the internal storage,
    210 they are never accessible to other apps.</p>
    211 
    212 
    213 
    214 
    215 
    216 <h2 id="WriteExternalStorage">Save a File on External Storage</h2>
    217 
    218 <p>Because the external storage may be unavailable&mdash;such as when the user has mounted the
    219 storage to a PC or has removed the SD card that provides the external storage&mdash;you
    220 should always verify that the volume is available before accessing it. You can query the external
    221 storage state by calling {@link android.os.Environment#getExternalStorageState}. If the returned
    222 state is equal to {@link android.os.Environment#MEDIA_MOUNTED}, then you can read and
    223 write your files. For example, the following methods are useful to determine the storage
    224 availability:</p>
    225 
    226 <pre>
    227 /* Checks if external storage is available for read and write */
    228 public boolean isExternalStorageWritable() {
    229     String state = Environment.getExternalStorageState();
    230     if (Environment.MEDIA_MOUNTED.equals(state)) {
    231         return true;
    232     }
    233     return false;
    234 }
    235 
    236 /* Checks if external storage is available to at least read */
    237 public boolean isExternalStorageReadable() {
    238     String state = Environment.getExternalStorageState();
    239     if (Environment.MEDIA_MOUNTED.equals(state) ||
    240         Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {
    241         return true;
    242     }
    243     return false;
    244 }
    245 </pre>
    246 
    247 <p>Although the external storage is modifiable by the user and other apps, there are two
    248 categories of files you might save here:</p>
    249 
    250 <dl>
    251   <dt>Public files</dt>
    252   <dd>Files that
    253 should be freely available to other apps and to the user. When the user uninstalls your app,
    254 these files should remain available to the user.
    255   <p>For example, photos captured by your app or other downloaded files.</p>
    256   </dd>
    257   <dt>Private files</dt>
    258   <dd>Files that rightfully belong to your app and should be deleted when the user uninstalls
    259   your app. Although these files are technically accessible by the user and other apps because they
    260   are on the external storage, they are files that realistically don't provide value to the user
    261   outside your app. When the user uninstalls your app, the system deletes
    262   all files in your app's external private  directory. 
    263   <p>For example, additional resources downloaded by your app or temporary media files.</p>
    264   </dd>
    265 </dl>
    266 
    267 <p>If you want to save public files on the external storage, use the
    268 {@link android.os.Environment#getExternalStoragePublicDirectory
    269 getExternalStoragePublicDirectory()} method to get a {@link java.io.File} representing
    270 the appropriate directory on the external storage. The method takes an argument specifying
    271 the type of file you want to save so that they can be logically organized with other public
    272 files, such as {@link android.os.Environment#DIRECTORY_MUSIC} or {@link
    273 android.os.Environment#DIRECTORY_PICTURES}. For example:</p>
    274 
    275 <pre>
    276 public File getAlbumStorageDir(String albumName) {
    277     // Get the directory for the user's public pictures directory. 
    278     File file = new File(Environment.getExternalStoragePublicDirectory(
    279             Environment.DIRECTORY_PICTURES), albumName);
    280     if (!file.mkdirs()) {
    281         Log.e(LOG_TAG, "Directory not created");
    282     }
    283     return file;
    284 }
    285 </pre>
    286 
    287 
    288 <p>If you want to save files that are private to your app, you can acquire the
    289 appropriate directory by calling {@link
    290 android.content.Context#getExternalFilesDir getExternalFilesDir()} and passing it a name indicating
    291 the type of directory you'd like. Each directory created this way is added to a parent
    292 directory that encapsulates all your app's external storage files, which the system deletes when the
    293 user uninstalls your app.</p>
    294 
    295 <p>For example, here's a method you can use to create a directory for an individual photo album:</p>
    296 
    297 <pre>
    298 public File getAlbumStorageDir(Context context, String albumName) {
    299     // Get the directory for the app's private pictures directory. 
    300     File file = new File(context.getExternalFilesDir(
    301             Environment.DIRECTORY_PICTURES), albumName);
    302     if (!file.mkdirs()) {
    303         Log.e(LOG_TAG, "Directory not created");
    304     }
    305     return file;
    306 }
    307 </pre>
    308 
    309 <p>If none of the pre-defined sub-directory names suit your files, you can instead call {@link
    310 android.content.Context#getExternalFilesDir getExternalFilesDir()} and pass {@code null}. This
    311 returns the root directory for your app's private directory on the external storage.</p>
    312 
    313 <p>Remember that {@link android.content.Context#getExternalFilesDir getExternalFilesDir()}
    314 creates a directory inside a directory that is deleted when the user uninstalls your app.
    315 If the files you're saving should remain available after the user uninstalls your
    316 app&mdash;such as when your app is a camera and the user will want to keep the photos&mdash;you
    317 should instead use {@link android.os.Environment#getExternalStoragePublicDirectory
    318 getExternalStoragePublicDirectory()}.</p>
    319 
    320 
    321 <p>Regardless of whether you use {@link
    322 android.os.Environment#getExternalStoragePublicDirectory
    323 getExternalStoragePublicDirectory()} for files that are shared or
    324 {@link android.content.Context#getExternalFilesDir
    325 getExternalFilesDir()} for files that are private to your app, it's important that you use
    326 directory names provided by API constants like
    327 {@link android.os.Environment#DIRECTORY_PICTURES}. These directory names ensure
    328 that the files are treated properly by the system. For instance, files saved in {@link
    329 android.os.Environment#DIRECTORY_RINGTONES} are categorized by the system media scanner as ringtones
    330 instead of music.</p>
    331 
    332 
    333 
    334 
    335 <h2 id="GetFreeSpace">Query Free Space</h2>
    336 
    337 <p>If you know ahead of time how much data you're saving, you can find out
    338 whether sufficient space is available without causing an {@link
    339 java.io.IOException} by calling {@link java.io.File#getFreeSpace} or {@link
    340 java.io.File#getTotalSpace}. These methods provide the current available space and the
    341 total space in the storage volume, respectively. This information is also useful to avoid filling
    342 the storage volume above a certain threshold.</p>
    343 
    344 <p>However, the system does not guarantee that you can write as many bytes as are
    345 indicated by {@link java.io.File#getFreeSpace}.  If the number returned is a
    346 few MB more than the size of the data you want to save, or if the file system
    347 is less than 90% full, then it's probably safe to proceed.
    348 Otherwise, you probably shouldn't write to storage.</p>
    349 
    350 <p class="note"><strong>Note:</strong> You aren't required to check the amount of available space
    351 before you save your file. You can instead try writing the file right away, then
    352 catch an {@link java.io.IOException} if one occurs. You may need to do
    353 this if you don't know exactly how much space you need. For example, if you
    354 change the file's encoding before you save it by converting a PNG image to
    355 JPEG, you won't know the file's size beforehand.</p>
    356 
    357 
    358 
    359 
    360 <h2 id="DeleteFile">Delete a File</h2>
    361 
    362 <p>You should always delete files that you no longer need. The most straightforward way to delete a
    363 file is to have the opened file reference call {@link java.io.File#delete} on itself.</p>
    364 
    365 <pre>
    366 myFile.delete();
    367 </pre>
    368 
    369 <p>If the file is saved on internal storage, you can also ask the {@link android.content.Context} to locate and
    370 delete a file by calling {@link android.content.Context#deleteFile deleteFile()}:</p>
    371 
    372 <pre>
    373 myContext.deleteFile(fileName);
    374 </pre>
    375 
    376 <div class="note">
    377 <p><strong>Note:</strong> When the user uninstalls your app, the Android system deletes
    378 the following:</p> 
    379 <ul>
    380 <li>All files you saved on internal storage</li>
    381 <li>All files you saved on external storage using {@link
    382 android.content.Context#getExternalFilesDir getExternalFilesDir()}.</li>
    383 </ul>
    384 <p>However, you should manually delete all cached files created with
    385 {@link android.content.Context#getCacheDir()} on a regular basis and also regularly delete
    386 other files you no longer need.</p>
    387 </div>
    388 
    389