This lesson teaches you to
You should also read
Open Android File Transfer. The next time that you connect your phone, it opens automatically. Unlock your phone. With a USB cable, connect your phone to your computer. On your phone, tap the 'Charging this device via USB' notification. Under 'Use USB for,' select File Transfer. An Android File Transfer window will open on your computer.
Android uses a file system that'ssimilar to disk-based file systems on other platforms. This lesson describeshow to work with the Android file system to read and write files with the
File
APIs.A
File
object is suited to reading or writing large amounts of data instart-to-finish order without skipping around. For example, it's good for image files oranything exchanged over a network.This lesson shows how to perform basic file-related tasks in your app.The lesson assumes that you are familiar with the basics of the Linux file system and thestandard file input/output APIs in
java.io
.Choose Internal or External Storage
All Android devices have two file storage areas: 'internal' and 'external' storage. These namescome from the early days of Android, when most devices offered built-in non-volatile memory(internal storage), plus a removable storage medium such as a micro SD card (external storage).Some devices divide the permanent storage space into 'internal' and 'external' partitions, so evenwithout a removable storage medium, there are always two storage spaces andthe API behavior is the same whether the external storage is removable or not.The following lists summarize the facts about each storage space.
Devices's local file system. File access includes the device's internal memory and any mounted external memory (for instance, SD cards or local network shared mounted by Android). All files and folders can be explored and played back by any other openBOXware application, including primarily the openBOXware media library. To access Android files and folders on Windows PC over WiFi, we are going to use the popular file manager ES File Explorer. To start off, install ES File Explorer if you haven’t already. Launch it, swipe from the left side of the screen and then select the option “Remote Manager” from the main menu.
Internal storage:
- It's always available.
- Files saved here are accessible by only your app by default.
- When the user uninstalls your app, the system removes all your app's files frominternal storage.
Internal storage is best when you want to be sure that neither the user nor other apps canaccess your files.
External storage:
- It's not always available, because the user can mount the external storage as USB storageand in some cases remove it from the device.
- It's world-readable, sofiles saved here may be read outside of your control.
- When the user uninstalls your app, the system removes your app's files from hereonly if you save them in the directory from
getExternalFilesDir()
.
External storage is the bestplace for files that don't require access restrictions and for files that you want to sharewith other apps or allow the user to access with a computer.
Tip: Although apps are installed onto the internal storage bydefault, you can specify the
android:installLocation
attribute in your manifest so your app maybe installed on external storage. Users appreciate this option when the APK size is very large andthey have an external storage space that's larger than the internal storage. For moreinformation, see App Install Location.Obtain Permissions for External Storage
To write to the external storage, you must request the
WRITE_EXTERNAL_STORAGE
permission in your manifest file:Caution:Currently, all apps have the ability to read the external storagewithout a special permission. However, this will change in a future release. If your app needsto read the external storage (but not write to it), then you will need to declare the
READ_EXTERNAL_STORAGE
permission. To ensure that your app continuesto work as expected, you should declare this permission now, before the change takes effect.However, if your app uses the
WRITE_EXTERNAL_STORAGE
permission, then it implicitly has permission to read the external storage as well.You don’t need any permissions to save files on the internalstorage. Your application always has permission to read andwrite files in its internal storage directory.
Save a File on Internal Storage
Open File System Android Phone
When saving a file to internal storage, you can acquire the appropriate directory as a
File
by calling one of two methods:getFilesDir()
- Returns a
File
representing an internal directory for your app. getCacheDir()
- Returns a
File
representing an internal directory for your app's temporarycache files. Be sure to delete each file once it is nolonger needed and implement a reasonable size limit for the amount of memory you use at any giventime, such as 1MB. If the system begins running low on storage, it may delete your cache fileswithout warning.
To create a new file in one of these directories, you can use the
File()
constructor, passing the File
provided by oneof the above methods that specifies your internal storage directory. For example:Alternatively, you can call
openFileOutput()
to get a FileOutputStream
that writes to a file in your internal directory. For example, here'show to write some text to a file:Or, if you need to cache some files, you should instead use
createTempFile()
. For example, the following method extracts thefile name from a URL
and creates a file with that namein your app's internal cache directory:Note:Your app's internal storage directory is specifiedby your app's package name in a special location of the Android file system.Technically, another app can read your internal files if you setthe file mode to be readable. However, the other app would also need to know your app packagename and file names. Other apps cannot browse your internal directories and do not haveread or write access unless you explicitly set the files to be readable or writable. So as longas you use
MODE_PRIVATE
for your files on the internal storage,they are never accessible to other apps.Save a File on External Storage
Because the external storage may be unavailable—such as when the user has mounted thestorage to a PC or has removed the SD card that provides the external storage—youshould always verify that the volume is available before accessing it. You can query the externalstorage state by calling
getExternalStorageState()
. If the returnedstate is equal to MEDIA_MOUNTED
, then you can read andwrite your files. For example, the following methods are useful to determine the storageavailability:Although the external storage is modifiable by the user and other apps, there are twocategories of files you might save here:
For example, photos captured by your app or other downloaded files.
Files that rightfully belong to your app and should be deleted when the user uninstalls your app. Although these files are technically accessible by the user and other apps because they are on the external storage, they are files that realistically don't provide value to the user outside your app. When the user uninstalls your app, the system deletes all files in your app's external private directory.
For example, additional resources downloaded by your app or temporary media files.
If you want to save public files on the external storage, use the
getExternalStoragePublicDirectory()
method to get a File
representingthe appropriate directory on the external storage. The method takes an argument specifyingthe type of file you want to save so that they can be logically organized with other publicfiles, such as DIRECTORY_MUSIC
or DIRECTORY_PICTURES
. For example:If you want to save files that are private to your app, you can acquire theappropriate directory by calling
getExternalFilesDir()
and passing it a name indicatingthe type of directory you'd like. Each directory created this way is added to a parentdirectory that encapsulates all your app's external storage files, which the system deletes when theuser uninstalls your app.For example, here's a method you can use to create a directory for an individual photo album:
If none of the pre-defined sub-directory names suit your files, you can instead call
getExternalFilesDir()
and pass null
. Thisreturns the root directory for your app's private directory on the external storage.Remember that
getExternalFilesDir()
creates a directory inside a directory that is deleted when the user uninstalls your app.If the files you're saving should remain available after the user uninstalls yourapp—such as when your app is a camera and the user will want to keep the photos—youshould instead use getExternalStoragePublicDirectory()
.Regardless of whether you use
getExternalStoragePublicDirectory()
for files that are shared orgetExternalFilesDir()
for files that are private to your app, it's important that you usedirectory names provided by API constants likeDIRECTORY_PICTURES
. These directory names ensurethat the files are treated properly by the system. For instance, files saved in DIRECTORY_RINGTONES
are categorized by the system media scanner as ringtonesinstead of music.Query Free Space
If you know ahead of time how much data you're saving, you can find outwhether sufficient space is available without causing an
IOException
by calling getFreeSpace()
or getTotalSpace()
. These methods provide the current available space and thetotal space in the storage volume, respectively. This information is also useful to avoid fillingthe storage volume above a certain threshold.However, the system does not guarantee that you can write as many bytes as areindicated by
getFreeSpace()
. If the number returned is afew MB more than the size of the data you want to save, or if the file systemis less than 90% full, then it's probably safe to proceed.Otherwise, you probably shouldn't write to storage.Note: You aren't required to check the amount of available spacebefore you save your file. You can instead try writing the file right away, thencatch an
IOException
if one occurs. You may need to dothis if you don't know exactly how much space you need. For example, if youchange the file's encoding before you save it by converting a PNG image toJPEG, you won't know the file's size beforehand.Delete a File
You should always delete files that you no longer need. The most straightforward way to delete afile is to have the opened file reference call
delete()
on itself.If the file is saved on internal storage, you can also ask the
Context
to locate anddelete a file by calling deleteFile()
:Open File System Android App
Note: When the user uninstalls your app, the Android system deletesthe following:
- All files you saved on internal storage
- All files you saved on external storage using
getExternalFilesDir()
.
However, you should manually delete all cached files created with
getCacheDir()
on a regular basis and also regularly deleteother files you no longer need.The Device File Explorer allows you to view, copy, and delete files on anAndroid device. This is useful when examining files that are created by your appor if you want to transfer files to and from a device.
Note: Most device data is not visible unless you are using a rooted device or anemulator with a standard Android (AOSP) system image (not one of the Google APIsor Google Play system images). And when using a connected device, be sure youenable USB debugging.To work with a device's file system, proceed as follows:
- Click View > Tool Windows > Device File Explorer or click theDevice File Explorer button in the tool window bar to open the Device File Explorer.
- Select a device from the drop down list.
- Interact with the device content in the file explorer window. Right-click on a file or directory to create a new file or directory, save the selected file or directory to your machine, upload, delete, or synchronize. Double-click a file to open it in Android Studio.Android Studio saves files you open this way in a temporary directory outside of your project. If you make modifications to a file you opened using the Device File Explorer, and would like to save your changes back to the device, you must manually upload the modified version of the file to the device.
Figure 1. The Device File Explorer tool window
When exploring a device's files, the following directories are particularlyuseful:
data/data/app_name/
- Contains data files for your app stored oninternal storage
sdcard/
- Contains user files stored onexternal userstorage (pictures, etc.)
Note: Not all files on a hardware device arevisible in the Device File Explorer. For example, in the
data/data/
directory, entries corresponding to apps on the device that are not debuggablecannot be expanded in the Device File Explorer.