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