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