Android data storage file and android Data Storage

Source: Internet
Author: User

Android data storage file and android Data Storage
In the previous article, we used SharedPreferences to save data in Android. SharedPreferences mainly saves the setting information of some applications or a small amount of user information when saving data, the String class information stored in the form of key-value has limitations. For example, if you need to save the images obtained from the network to the local database as the cached data, and the number of images is large, SharedPreferences cannot meet your needs, in this case, you need to save the files used by all platforms. In Android, saving data to a disk as a file is similar to that on other platforms. This article will introduce how to use java. io. Files API functions to read and write Files. Choose "internal storage" or "External Storage": All Android devices have two file storage areas: "internal" and "external. These names came from the early days of Android, when most devices provided built-in non-volatile memory (memory), plus a removable storage medium such as micro SD card (external storage ). Currently, Android devices have a large storage space, such as 16 GB or 32 GB. Here, 16 GB and 32 GB refer to the total disk size, it is equivalent to a brand new hard disk of your new computer. The android system will be burned on this disk when the mobile phone leaves the factory. The android system will partition the entire disk and provide part of it for the android system to store system files, similar to the windows system disk, however, there are more strict permissions than those on windows. Users cannot access this part of the file at Will (except root). This part is called internal storage, and the rest of users can use it freely, when a mobile phone connects to a computer, it only displays this part of the file, called external storage, which is equivalent to other windows disks (such as D disks). Of course, some users add a micro-SD card, this part is also considered as external storage, which is equivalent to an external hard disk on windows. There is a difference between internal and external storage. When using internal storage, you need to pay attention to their respective features: Internal Storage:

  • Always available;
  • By default, saved files can only be accessed by apps that save files. applications cannot access each other and can only access their own files.
  • When the application is uninstalled, the files saved by the application will be completely cleared;
  • If the file you want to save is safe and won't be read by users and other applications, you can choose internal storage.
External Storage:
  • Not necessarily exists. For example, some mobile phones only store internal storage and do not store external storage, and the user does not install the micro-SD card. In this case, external storage is unavailable;
  • The read and write operations are fully open, so the data you save may be read by users and other programs;
  • When you uninstall an application, only the directory files obtained through getExternalFilesDir () are deleted;
  • If you do not need to control the access permission of your files and can allow other applications or users to view them, external storage is a good choice;
 

Note: by default, applications are installed in internal storage. You can specify the android: installLocation attribute in the AndroidManifest. xml file so that your applications can be installed in external storage. This installation option is very practical for users. When some applications are very large and the internal storage space is insufficient, users can install the applications in the external storage space.

Obtain external storage permissions: To store files in external storage, you must first obtain the read and write permissions of external storage. The permission declaration is in the AndroidManifest. xml file. The Code is as follows:
<manifest ...>    <uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/>    ...</manifest>

Note: All applications now have the read permission for external storage by default. the default permission may be changed in later Android versions, so it is best to explicitly declare the read permission in AndroidManifest, the read permission statement is as follows:

<manifest ...>    <uses-permissionandroid:name="android.permission.READ_EXTERNAL_STORAGE"/>    ...</manifest>
In addition: 1. The Write Permission implies the read permission; 2. the internal storage does not require permission declaration, and the application has the permission to read and write files for the internal storage by default; save to the internal storage: you need to create a file for file storage. When saving the file to the internal storage, you can obtain the internal storage file through the following two methods:

1. File getFilesDir ();

Returns a file directory that stores application data. All files created using openFileOutput (String, int) are saved in this directory. This directory is probably: data/package name/files. For example, the pods app is: data/com. wandoujia. phoenix2/files/
2. File getCacheDir ();
Return a file directory that stores cached files of applications. When the system space is insufficient, these files will be deleted first. This directory is probably: data/package name/cache. For example, the pods app is: data/com. wandoujia. phoenix2/cache/

Note: the deletion of cached files should not rely on the system to delete it. The best way is to set a maximum value for your application cache, such as 1 M, when this value is reached, you should delete some cached files so that the space can be reused.

When you want to write a File into the internal storage, you must first create a File. You can use the File constructor to input the path obtained by the above two methods as the parameter, you can easily create a file, for example:

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

Then, use the file above to create a file stream and write the file. Of course, you may prefer the following method to create a FileOutputStream by calling openFileOutput () and then write the file. The Code is as follows:

String filename ="myfile";Stringstring="Hello world!";FileOutputStream outputStream;try{  outputStream = openFileOutput(filename,Context.MODE_PRIVATE);  outputStream.write(string.getBytes());  outputStream.close();}catch(Exception e){  e.printStackTrace();}

When you need to create a cache file, you can use the following method:

File file = newFile(context.getCacheDir(), filename);

Alternatively, you will prefer the following method: Use the creatTempFile method of File to create a temporary File in the cache directory. The File suffix is. tmp:

publicFile 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: Normally, files stored in your application will not be accessed by other applications, because the first thing you need to know is the package name and file name of your application, next, you need to obtain the access permission for this file. Technically, if the file you store is opened with the file read permission, other applications can read the file, unless you set the file to read/write, otherwise, other programs cannot read your files, so the File Permission is Context. MODE_PRIVATE must be set.

Save to external storage: to save to external storage, first check whether the external storage exists and has the remaining space, because the external storage may be unplugged or is connected to a computer, therefore, when you want to save files in external storage, the first step is to check whether the external storage is mounted. You can call the getExternalStorageState () method to check whether the external storage is mounted. If the returned status is Environment. MEDIA_MOUNTED indicates that it has been mounted and can be read and written. For example, the following code:
/* Checks if external storage is available for read and write */publicboolean isExternalStorageWritable(){    String state =Environment.getExternalStorageState();    if(Environment.MEDIA_MOUNTED.equals(state)){        returntrue;    }    returnfalse;}/* Checks if external storage is available to at least read */publicboolean isExternalStorageReadable(){    String state =Environment.getExternalStorageState();    if(Environment.MEDIA_MOUNTED.equals(state)||        Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)){        returntrue;    }    returnfalse;}
Although files stored in external storage can be accessed by users and other programs, you need to treat files stored in external storage in two types: public files: these files are fully developed, you can access other applications or users. When your application is uninstalled, this part of the file will not be deleted, such as your photo program, A user's photo will not be deleted because the user has uninstalled the application. For example, if the user views the video software, the downloaded video cannot be deleted because the user has uninstalled the app. Private files: these files belong to your application and are not available to other applications and have no value for exploitation, although these files are open to users and other programs. This type of file should be deleted when the application is uninstalled. Otherwise, it will waste user space, such as cache files and map resources. If you want to save a public file to external storage, you can use Environment. in java, the public static File getExternalStoragePublicDirectory (String type) method is used to obtain the public directories of external storage. There are several types of public directories. Different folders are returned Based on the type you enter. The types include:
Public static String DIRECTORY_ALARMS Standard ringtones
Public static String DIRECTORY_DCIM Storage directory of camera photos or video files
Public static String DIRECTORY_DOWNLOADS Download directory
Public static String DIRECTORY_MOVIES Movie catalog
Public static String DIRECTORY_MUSIC Music directory
Public static String Directory_configurications Prompt audio directory
Public static String DIRECTORY_PICTURES Image directory
Public static String DIRECTORY_PODCASTS Podcast directory
Public static String DIRECTORY_RINGTONES Ringtone directory

The most common DIRECTORY_PICTURES directory is/mnt/sdcard/Pictures. For example, if you want to store an image, create an image file in the public directory where the image is stored:

publicFile getAlbumStorageDir(String albumName){    // Get the directory for the user's public pictures directory.     File file =newFile(Environment.getExternalStoragePublicDirectory(            Environment.DIRECTORY_PICTURES), albumName);    if(!file.mkdirs()){        Log.e(LOG_TAG,"Directory not created");    }    return file;}

If you want to save private data to external storage, you can call:

Public abstract File getExternalFilesDir (String type) method to obtain the external storage path. The path is:

/Mnt/sdcard/Android/data/your_package/type. The type is the same as above. Select the file type you want to save. The following is an example of creating a private image file:

publicFile getAlbumStorageDir(Context context,String albumName){    // Get the directory for the app's private pictures directory.     File file =newFile(context.getExternalFilesDir(            Environment.DIRECTORY_PICTURES), albumName);    if(!file.mkdirs()){        Log.e(LOG_TAG,"Directory not created");    }    return file;}

If the type does not have the type you need, you can enter null. The returned result is the root directory of the private directory of the external storage directory of your application.

Note: files created using the getExternalFilesDir (String type) method will be cleared when the user clears data or when the application is uninstalled. files created using the getExternalStoragePublicDirectory (String type) method will not. In addition, no matter which method you use to create an external storage file for the application, pay attention to the correctness of the type so that the system can process the file correctly, for example, if the file you saved is a ringtone type, in DIRECTORY_RINGTONES, the system MediaScanner classifies the file as a ringtone rather than a music when performing a multimedia scan. Query the remaining space: If you know the size of the File you want to save in advance, you can use File. getFreeSpace () or File. the getTotalSpace () method is used to estimate whether the storage space can be accommodated. This avoids IOException when there is not enough storage space. However, sometimes File. the available space obtained by getFreeSpace () is not necessarily available for you. the size obtained by getFreeSpace () is several Mb larger than your file size or the file system has more than 10% of the remaining space. In this case, the file may be saved normally. Otherwise, the file may fail to be saved. Note: Before saving the file, you do not need to check the available space, but capture IOException when writing the file. This method is used to replace the check of the space size, if you do not know how much space you need. Delete a File: when you no longer need a File, you need to delete it. The most direct method is to directly call the File. delete () method to delete it. If the file is stored in the internal storage, you can also call the Context. deleteFile (String name) method class to delete the file. When the user uninstalls your application, the Android system will delete your following files: 1. All files saved in the internal storage; 2. All files saved in getExternalFilesDir () directory external storage files; Note: You need to regularly and manually clear files cached through getCacheDir () and files that are no longer needed. Summary: The above describes how to save files in the Android system. File storage can be divided into external storage and Internal Storage Based on the storage location, according to the openness and availability of applications, there are private and public types, as well as file storage methods and some precautions. If you have any questions, please leave a message or reply to my public account: coder_online.

If you are interested in programming, want to learn more about programming, solve programming problems, and want the system to learn a certain kind of development knowledge, we have a master of java here, C ++/C master, windows/Linux master, android/ios Master, please pay attention to my public account: programmer InterAction alliance or coder_online, and Daniel online provides services for you.

Related Article

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.