Official Android development documentation Training series course Chinese version: data storage file storage

Source: Internet
Author: User

Official Android development documentation Training series course Chinese version: data storage file storage

The file system used by Android is similar to the disk-type file system on other platforms. This section describes how to use FileAPI to read and write files in the Android file system.

A File object is suitable for reading or writing a large amount of data from start to end. It is not suitable for Skip-type access, that is, random access. For example, this is suitable for image files or any network-based data exchange.

This section describes how to perform the most basic file-related tasks in the APP. This lesson assumes that you have the basics of the Linux File System and the input and output of Java standards.

Select internal or external storage

All Android devices have two file storage partitions: "internal" and "external. These terms come from earlier Android versions. When most devices provide built-in fixed memory, a removable storage media such as micro SD card (external memory) will be added ). Some devices have fixed storage space divided into "internal" and "external" partitions, so there are still two storage spaces even if there is no removable storage media. The API shows the same behavior, regardless of whether the external memory is removable or not. The following is a summary of the facts of each storage space.

Internal storage:

It is always available. By default, the APP saves the file here and only allows the APP to access it. If the user uninstalled your APP, the system will remove all the APP files from it.

If you do not want users or other apps to access your files, internal storage is a suitable place.

External storage:

It is not always available because the user may mount the external storage as a USB memory and may be removed from the device. It is globally accessible, so if the file is stored here, it may be accessed out of your control. When you uninstall your APP, the system will only delete the files you saved in the getExternalFilesDir () returned directory.

If you do not need access restrictions, external memory is a suitable place. It can access your files from another APP, or you can access these files from a computer.

Note:Although the APP will be installed in the internal memory by default during installation, you can specify the location where the APP is installed by specifying the android: installLocation attribute in the configuration file. If the size of the APK is large and the external storage space is larger than the internal storage space, you will appreciate this. For more information, see App Install Location.

Obtain external memory Permissions

To write files to external storage, you must request the WRITE_EXTERNAL_STORAGE permission in the inventory file.


      
   
        ...
   
  

Warning:Currently, all apps have the ability to access external storage without the need to specify permissions. However, this will be changed in future releases. If your APP needs to read data from external storage (not written), you need to declare the READ_EXTERNAL_STORAGE permission to ensure that your APP can continue to work in future versions, you should declare this permission before the change takes effect.


       
    
      android:name="android.permission.READ_EXTERNAL_STORAGE" />    ...
    
   

However, if your APP uses the WRITE_EXTERNAL_STORAGE permission, it will implicitly include the permission to read external memory.

You do not have any permissions to save files in internal storage. Your application always has the right to read and write files to the internal storage directory.

Save files to internal storage

When you want to save the File to the internal storage, you can use one of the following two methods to obtain a suitable directory object File:

GetFilesDir () returns a File object representing the internal storage directory of the APP.

GetCacheDir () returns a File object, which represents the temporary File cache directory of the APP in the internal memory. To ensure that the file can be deleted when it is no longer needed, a reasonable size limit, such as 1 MB, should be implemented for the number of memories at any given time. If the system starts to run slowly on memory, it may delete your temporary files without warning.

To create a File in these directories, you can use the File () constructor to pass the preceding method directory to the File constructor to specify the internal storage directory. Like this:

File file = new File(context.getFilesDir(), filename);

Alternatively, you can call openFileOutput () to obtain a FileOutputStream object to write the file to the internal storage. Here is an example of how to write some text to a 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();}

Alternatively, if you need to cache some files, you should use createTempFile (). For example, the following method extracts the file name from the URL and creates a file in the internal cache directory using this name:

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 internal storage path of the APP is specified by the package name of the APP and placed in a special location in the Android file system. Technically speaking, other apps can read your internal files if the file mode you set is readable. However, other apps should also know the package name and file name of your APP. Other apps cannot browse your internal directories, and do not have the access and write permissions, unless you have set the file to and read/write. Therefore, once you use the MODE_PRIVATE mode for internal storage files, other apps will never be able to access these files.

Save files to external storage

Because external memory may be unavailable, for example, when you mount it to a PC or remove the SD card, you should check whether it is available before accessing it. You can use the getExternalStorageState () method to query the external memory status. If the returned status is MEDIA_MOUNTED, you can read and write files. For example, the following method is used to check whether the memory is available:

/* Checks if external storage is available for read and write */public boolean isExternalStorageWritable() {    String state = 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 memory can be modified by users or other apps, there are two types of file storage that you may use.

Public file:
In this case, the file should be accessible by other apps or users. When the user uninstalls your APP, these files will be retained to the user.

For example, a photo captured by the APP or a downloaded file.

Private file:
These files will belong to your APP and will be deleted when you uninstall the APP. Although these files can be accessed by users or other apps technically, they are stored in external storage. In fact, these files are not provided to users outside the APP. When the APP is uninstalled, the system deletes the files from the external storage.

For example, the APP downloads additional resources or temporary media files.

If you want to save public files in external storage, use the getExternalStoragePublicDirectory () method to obtain a File object that represents an appropriate directory. The parameters carried in this method specify the file type you need to store, so that the system can logically organize other public files, such as DIRECTORY_MUSIC or DIRECTORY_PICTURES, public music and images are represented respectively:

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 a private file, you can call the getExternalFilesDir () method to obtain the appropriate directory and then pass it the name of your desired directory type. Each directory is created and added to the parent directory in this way, so as to encapsulate all the files in the external storage and delete them when the user uninstalls the APP.

You can use this method to create a personal album directory:

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 you do not have a pre-defined subdirectory name for the file, you can call getExternalFilesDir () and input a Null value. This will return the root directory of the APP's private directory on the external storage.

Remember that the directories created in the getExternalFilesDir () Directory will be deleted as the APP is uninstalled. If you want to keep these files after deletion, for example, if your APP is a camera APP and you want to keep these photos, you should use the getExternalStoragePublicDirectory () method.

Whether you are using getExternalStoragePublicDirectory () to share files or using getExternalFilesDir () to protect files in your APP, it is very important that you use the constants provided by the API, such as DIRECTORY_PICTURES, as the directory name. The names of these directories can be suitable for the system. For example, if the file is stored in the DIRECTORY_RINGTONES directory, the system media scanner recognizes it as a ringtone file rather than a music file.

Query the remaining space

If you can know in advance how much data you have saved, you can query whether there is enough space to use by calling getFreeSpace () or getTotalSpace. These methods provide both the current available space and the total disk capacity, which helps prevent the filled disk capacity from exceeding the fixed threshold value.

However, the system does not guarantee that you can write data equivalent to the remaining space size returned by getFreeSpace. If the returned number is several MB, which is larger than the data size you want to store, or the current usage capacity of the system is less than 90% of the total capacity, the processing may be safe now. Otherwise, you may not be suitable for writing data to the memory.

Note:If you do not check the available space before saving the file, you can try to write the file in the correct way. If the event occurs, it may cause an IOException. If you do not know the exact space you need, you may need to do so. For example, if you change from PNG encoding to JPEG encoding before storing a file, you may not know the file size in advance.

Delete an object

You should delete files when they are no longer needed. The most straightforward way is to have a reference to an opened file and then call its delete () method.

myFile.delete();

If the file is stored in the internal storage, you can also ask the Context to locate the file and then call deleteFile () to delete the file.

myContext.deleteFile(fileName);

Note:When you uninstall your APP, the Android system will delete the following files:

All files stored in internal memory

All files stored in the external memory under the getExternalFilesDir () Directory

In any case, you should manually delete all cached files on a regular basis. Even if the files are created using the getCacheDir () method, you should also regularly delete other files that you no longer need.

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.