Android file storage

Source: Internet
Author: User

The Android file system is similar to other platform disk-based file systems, and this tutorial describes how to use file-related APIs to read and write on an Android file system.

The file object is suitable for reading and writing a large amount of streaming data, a piece of file or other file network transmission.

This tutorial will show you how to perform basic file operations in the app and assume that the reader has a basis for the file input and output of the Linux file system and Java standards.

Select internal storage or external storage

All Android devices divide the file storage area into two parts: internal storage and external storage. The designation originated from an earlier Android system, when most devices had a built-in immutable memory (internal storage), and a removable storage medium, such as an SD card (external storage), which would habitually divide the permanent storage space into a "" internal and external, and regardless of whether external storage can be removed, the API behavior of both parts of the storage space is the same. The following separately summarizes the characteristics of each storage space:

Internal storage

1. Always available

2. The files within the internal storage space are accessible by default only by your app

3. When the user uninstalls your app, the system removes all your app-related files from the internal storage space

Internal storage is the best choice when you want users and other apps to have no access to your files.

External storage

1. Not always available because users may store external storage as USB and in some cases even remove external storage from the device

2. It is accessible to everyone, and the files stored here can be accessed by other applications

3. When the user uninstalls your app, the system simply removes the app-related files stored in the path obtained through Getexternalfilesdir ()

External storage is the best option when your files do not require access restrictions, or if you want to share files with other apps, or allow users to access it from a computer.

Tips

Although the app is installed to internal storage by default, you can install the app to an external storage space by specifying the Android:installlocation property in Androidmanifest. Users may prefer to do this when the APK file is large and the external space is larger than the internal space. For more information, please refer to app InstallLocation.

Permission to get External storage

In order to write data in an external storage space, you need to include permissions in the Androidmanifest file: Write_external_storage, as follows

<manifest ...> <uses-permission android:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/> ... </man Ifest>

Note : The app will now gain the ability to read external storage without having to provide special permissions, however, this may change in later releases. If your app needs to read external storage (but does not need to write), you need to declare read_external_storage permissions. Before this change occurs, in order to ensure that the application continues to work as expected, it is better to declare the Read permission now, as follows:

<manifest ...> <uses-permission android:name= "Android.permission.READ_EXTERNAL_STORAGE"/> ... </mani Fest>

However, if the app declares the Write_external_storage permission, it defaults to the permission to read the external storage space.

If you want to save the file to an internal storage space, you do not need to declare any permissions. Because the app itself has permissions to read and write to the internal storage space.

Save a file to an internal storage space

When saving a file to an internal storage space, you can obtain an appropriate directory as file using either of the following methods:

Getfilesdir ()

Returns a File object representing the internal directory for your app.

Getcachedir ()

Returns a File object representing the internal temporary cache files directory for your app. You need to set a reasonable size for the file directory, such as 1M, and make sure to delete the files when you don't need them. If the system is running out of storage space, the cached file may be deleted without warning.

If you want to create a file under an internal storage directory, you can use the file () constructor to pass in a file object obtained using one of these two methods, which specifies the path to the internal store. For example:

File File = new file (Context.getfilesdir (), filename);

Alternatively, you can call Openfileoutput () to get a fileoutputstream to write to a file under the internal storage path, and the following example shows how to write some text to the file:

String filename = "myfile"; String string = "Hello world!";  FileOutputStream outputstream;try {outputstream = openfileoutput (filename, context.mode_private);  Outputstream.write (String.getbytes ()); Outputstream.close ();} catch (Exception e) {e.printstacktrace ();}

Or, if you need to cache some files, you should use Createtempfile (). For example, the following example extracts the file name from a URL, and then creates a file named after the file name in the app's internal cache directory.

Public file GetTempFile (context context, String URL) {file file;        try {String fileName = uri.parse (URL). getlastpathsegment ();    File = File.createtempfile (FileName, NULL, Context.getcachedir ()); catch (IOException e) {//Error while creating file} return file;}
Note : The app's internal storage directory is located on the Android file system in a specific location determined by the app package name, and technically, if your file is set to readable, other apps can read your internal files, but other apps need to know the package name and file name of your app. If your file is not set to read/write, then other apps cannot access the app's internal directory and read and write your files. As long as the mode_private mode is used, other apps cannot be accessed.

saving files to an external storage space

Because external storage space is sometimes unavailable, such as when you connect an external storage space to a PC or an SD card is removed, you should check its availability when you access it. You can usually use Getexternalstorgestate () to query the state of an external storage space, and if the status is media_mounted, you can read and write files. Here's an effective way to check if the external storage space is available:

/* Checks If external storage is available for read and write */public Boolean isexternalstoragewritable () {String sta    Te = Environment.getexternalstoragestate ();    if (Environment.MEDIA_MOUNTED.equals (state)) {return true; } return false;}  /* Checks If external storage is available to at least read */public Boolean isexternalstoragereadable () {String state    = Environment.getexternalstoragestate ();        if (Environment.MEDIA_MOUNTED.equals (state) | |    Environment.MEDIA_MOUNTED_READ_ONLY.equals (state)) {return true; } return false;}

Although external storage can be modified by users and other applications, there are two types of files that can be saved here:

Public files

These files are accessible to users or other apps, and are retained and accessible to users when they uninstall your app. For example, photos taken by your app or downloaded files.

Private files

This type of file belongs only to your app and is deleted as the app is uninstalled. Because these files are stored externally, these files are technically accessible to users and other applications, but this is of little value to users outside your app. When the user uninstalls the app, all files under the external private directory to which the app belongs are deleted. For example, the app downloads additional resource files or temporary multimedia files.

If you want to save the public file on an external storage space, you can use the Getexternalstoragepublicdirectory () method to get a file object that represents the appropriate directory for the outer space. This method requires a parameter to specify the type of file you are saving so that it can be categorized with other public files. The parameter type has Directory_music or directory_pictures, and so on. For example:

Public File Getalbumstoragedir (String albumname) {//Get the directory for the user ' s public pictures directory. File File = new file (Environment.getexternalstoragepublicdirectory (environment.directory_pictures), albumName)    ;    if (!file.mkdirs ()) {LOG.E (Log_tag, "Directory not created"); } return file;

If you want to save files that are private to the app, you can call Getexternalfilesdir () to get the appropriate file directory and pass in a parameter of the specified file type. Directories created in this way are added to the directory that encapsulates all of the app's external storage files, and are deleted by the system when the user uninstalls the app. The following example can be used to create a directory for a personal album:

Public File Getalbumstoragedir (context context, String Albumname) {//Get the directory for the app ' s private pictures     Directory.    File File = new file (Context.getexternalfilesdir (environment.directory_pictures), albumname);    if (!file.mkdirs ()) {LOG.E (Log_tag, "Directory not created"); } return file;

If the predefined subdirectory is not suitable for our files, you can call Getexternalfilesdir () and pass in NULL, which returns the root directory of the app's private directory on the external storage space.

Keep in mind that directories created with the Getexternalfilesdir () method are removed as the app is uninstalled. If you want to use these files after the app is uninstalled, such as a photo app, we want to save the photos after uninstalling, then we should use Getexternalstoragepublicdirectory ().

Whether you use Getexternalstoragepublicdirectory () to save a shared file or use Getexternalfilesdir () to save your app's private files, it's important to use the directory name provided by the API constants whenever possible. such as directory_pictures, these directory names can ensure that the system correctly treats the files inside. For example, files stored in the Directory_ringtones type are recognized by the system as ringtones rather than music.

Query the remaining space

If you know in advance the size of the file you want to save, you can avoid ioexception by calling Getfreespace () or Gettotalspace () to determine if there is enough space. These methods can obtain the current available space and the size of the total capacity, which is useful for storing files on storage spaces above a certain threshold.

However, the system does not guarantee that files can be written to the Getfreespace () size, and if the remaining space is a few meters larger than the file you want to store, or less than 90% of the storage space is used, it is generally safe to keep the file, otherwise it is best not to write to the file again.

Note : In fact, it is not mandatory to query the remaining space before saving the file. You can simply try to write to the file and then capture IOException, if you don't know in advance how much storage space you need. For example, when you convert a PNG image to JPEG, you don't know beforehand what the size of the resulting picture is.

Deleting Files

You should delete the file when you no longer need it, the most straightforward way is by calling the file's delete () method.

Myfile.delete ();

If the file is stored on an internal storage space, you can also call the DeleteFile () method of the context to locate and delete the file.

Mycontext.deletefile (FileName);

Note : When the user uninstalls the app,android system, the following files are deleted:

1. All files stored in the internal storage space

2. All files saved in the external storage directory obtained by Getexternalfilesdir ()

However, you should periodically delete all cache files created through Getcachedir () and those that are no longer in use.


Original address: http://developer.android.com/training/basics/data-storage/files.html













Android file storage

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.