Save files for Android data

Source: Internet
Author: User

Preface: The previous article wrote the use of Sharedpreferences in Android to save data, sharedpreferences when saving data is mainly to save some application settings information or a small amount of user information, And it is the information of the string class saved in the form of Key-value, which is more limited.

For example, you need to save images from the network to local as cached data, and the number is larger. Sharedpreferences will not be able to meet your needs, this time will be used to basically all the platform will be used to save files.


Saving data to disk as files in Android is basically similar to other platforms. This article will show you how to use Java.io.Files's API functions for file read and write operations.
Select internal storage or external storage:
All Android devices have two file storage areas: "Internal" and "external" storage. These names come from the early days of Android. At that time most devices provided built-in nonvolatile memory (memory). Plus a removable storage medium such as a micro SD card (external storage). Today's Android devices are basically built-in storage spaces that are very large, for example, 16g or 32g. Here the 16g and 32g refers to the total disk size, equivalent to the new computer you bought a brand-new hard disk. The Android system is burned on this disk when the phone is shipped out, and the Android system will partition the entire disk. Some of the system files that are available to the Android system, like Windows, are more restrictive than those on Windows. Users are not allowed to access this part of the file (except root), which is called internal storage, and the rest of the users are free to use. When the phone is connected to the computer, it is only this part of the file that is found. called external storage. Equivalent to other disks on Windows (for example, D), and of course some users are adding a MICRO-SD card. This part is also the external storage, equivalent to the Windows external hard disk bar.
There is a difference between internal storage and external storage. You need to pay attention to their characteristics when using them:
Internal storage:
    • There is always a usable;
    • Saved files By default can only be visited by the app where the files are saved, and the apps can't access each other, just visit their saved files.

    • When the app is uninstalled, the files that are saved are completely erased.
    • Assuming that the files you want to save are very secure and will not be read by users and other applications, you can choose to store them in a way that is internal.
External storage:
    • Not necessarily exist, for example, some mobile phone factory is only internal storage, no external storage, the user did not install the MICRO-SD card, then the external storage is not available.
    • Read-write is completely open, so your saved data may be read by users and other programs;
    • Uninstalling the app only removes the folder file that was obtained through Getexternalfilesdir ();
    • Assuming that your file does not need to control access permissions, can agree to other applications or users to view, then the external storage is a good choice;

Note: By default applications are installed to internal storage, you can specify the Android:installlocation property in the Androidmanifest.xml file so that your application can be installed on external storage.

This installation option is useful for users, when some applications are large and the user can install the app to an external storage space when there is not enough internal storage.


Get External storage permissions: to store files on external storage first to obtain read and write permissions for external storage, the permissions are declared in the Androidmanifest.xml file, with the code such as the following:
<manifest ...> <uses-permissionandroid:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/> ... </ Manifest>

Note: All applications now have read access to external storage by default, and you do not need to declare them in the Androidmanifest.xml file. However, this default permission may change in the future Android version number. So it is advisable to explicitly read the permission declaration in the androidmanifest, lest the program fail in the later version number, read the permission declaration such as the following:

<manifest ...> <uses-permissionandroid:name= "Android.permission.READ_EXTERNAL_STORAGE"/> ... </ Manifest>
In addition: 1, write permission implies Read permission, 2, internal storage does not need permission to declare, the application for internal storage by default has read and write file permissions;
Save to internal storage: File storage requires file creation. When saving files to internal storage you are able to obtain internal storage files via the following two methods:

1, File getfilesdir ();

Returns a file folder. This folder holds the data for the application, and the files created by Openfileoutput (String, int) are saved under this file folder.

This folder is probably: data/data/package name/files, for example pea pod application is: data/data/com.wandoujia.phoenix2/files/

2, File getcachedir ();
Returns a file folder, which holds the application cache file, which is first deleted when the system is running out of space.

This folder is probably: data/data/package name/cache. For example, the Pea pod application is: data/data/com.wandoujia.phoenix2/cache/ Note: The deletion of cache files should not rely on the system to remove it, the best way is to give your application cache set a maximum value, such as 1M, When this value is reached you should delete some of the cache files so that you can reuse this space.

When you want to write a file in the internal store, you first create a file that is able to pass through the file's constructor. It is very convenient to create a file by passing in the path obtained by the above two methods as a parameter. Like what:

File File = NewFile (Context.getfilesdir (), filename);

The file stream is then created from the files above. Write the file. Of course you might prefer to create a fileoutputstream by calling Openfileoutput () in the following way. Then write the file with code such as the following:

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 do this in the following ways:

File File = NewFile (Context.getcachedir (), filename);

Or. You will prefer the following way. Create a temporary file in the cache folder through the file's Creattempfile method, with the suffix of. 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: Typically, your application's internal storage files are not visited by other applications. Since access to other programs requires you to know the package name and file name of your application, you need to obtain access to your file.

It is technically assumed that the files you have stored open the file Read permission other applications can read, unless you set the file to be read-write, or else the program is unable to read your files, so file permissions context.mode_private must be set.


Save to external storage: Save to external storage first check that the external storage exists and that there is space left, as external storage may be unplugged. Or is connected to the computer, so when you want to save the file in the external storage The first step is to check whether the external storage is hanging, you can call the Getexternalstoragestate () method to see if the external storage is mounted, assuming the return status is Environment.media _mounted. Indicates that it is already hanging and can read and write. For example, the following code:
/* Checks if external storage is available for read and write */publicboolean IsE Xternalstoragewritable () {    String State =environment.getexternalstoragestate ();    if ( Environment.MEDIA_MOUNTED.equals (state)) {        returntrue;   }    Returnfalse;} /* Checks If external storage is available to at least read */publicboolean isexternalstoragereadable () {    Stri ng State =environment.getexternalstoragestate ();    if (Environment.MEDIA_MOUNTED.equals | |         Environment.MEDIA_MOUNTED_READ_ONLY.equals (state) {        returntrue;    }    Returnfalse;} 
While externally stored files can be visited by users and other programs, you need to treat externally stored files in two categories: Public files: This type of file is completely developed. Access to other applications or users. This part of the file will not be deleted when your app is uninstalled. For example, your camera program. Users take photos will not be removed because the user uninstalled the app and delete photos, but also to see the video software, the user downloaded the video can not be removed due to uninstall the two.
Private files: This type of file is proprietary to your application and is not available to other applications, and no matter what the value is. Although this part of the file is open to users and other programs. This type of file should be deleted when the application is uninstalled. Otherwise, it will create a waste of user space, such as some cache files, map resources and so on.
Suppose you want to save a common file to external storage that you can pass in Environment.java: public static file Getexternalstoragepublicdirectory (String type) Method gets the public folder for external storage, there are several types of public folders, and different folders are returned depending on the type you enter, type types are:
public static String Directory_alarms Standard Ringtone Folder
public static String Directory_dcim Storage folder for camera photo or video files
public static String Directory_downloads Download folder
public static String Directory_movies Movie Folder
public static String Directory_music Music folder
public static String Directory_notifications Cue sound folder
public static String Directory_pictures Picture folder
public static String Directory_podcasts Podcasts Folder
public static String Directory_ringtones Ringtone Folder

The most common Directory_pictures folder for everyone is:/mnt/sdcard/pictures. For example, if you want to store a picture, create a picture file in the public folder where the image is stored externally:

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;

Suppose you want to save a private type of data to an external store, by calling Context.java in:

The public abstract File getexternalfilesdir (String type) method gets the external storage path, with the path:

/mnt/sdcard/android/data/data/your_package/type  ,type Ibid, depending on the type of file you want to save. Here's an example of creating a private picture file:

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

Assuming that the type does not have the types you need, you can enter NULL. This returns the root folder of the private folder of your application's external storage folder.

Note: Files created with the Getexternalfilesdir (String type) method are purged by the system when the user clears the data or when the application unloads. The file created by the getexternalstoragepublicdirectory (String type) method does not. In addition, no matter which method you use to create the application external storage file. Note the correctness of type types so that they can be handled correctly when the system is processed, for example, if you save a file that is a ringtone type, under Directory_ringtones. The system Mediascanner the file as a ringtone instead of music when doing a multimedia scan.
To query the remaining space:
Suppose you know in advance the size of the file you want to save. You can use the File.getfreespace () or File.gettotalspace () method to estimate whether storage space fits. This will prevent IOException from appearing when there is not enough storage space. However, sometimes the available space through File.getfreespace () is not necessarily so much for you to use, assuming that the size obtained by File.getfreespace () is larger than your file by a few m or the file system has more than 10% of the remaining space, Saving the file may work as expected, or it may fail to save.

Note: You do not need to check the free space before you save the file. Instead of capturing IOException when writing to a file, this method replaces the space-size check. Suppose you don't know how much space you need.


Delete files: When you no longer need a file you need to delete it, the most straightforward way is to directly call the File.delete () method to delete. Suppose this file is stored on the internal storage. You can also call the Context.deletefile (String name) method class to delete the file.
When the user uninstalls your app, the Android system will delete your files: 1. Save all files stored internally. 2, all stored in the Getexternalfilesdir () folder external storage files;
Note: You need to manually clean up files that are cached through Getcachedir () and files that are no longer needed.
Summary: The above explains the knowledge of file preservation in the Android system, the file preservation is divided into external storage and internal storage according to the location, according to the openness and the availability of the application is divided into private type and public type. There are also ways to save files and some caveats. Netizens have any doubts please leave a message or reply to my public number: Coder_online.

Everyone assumes interest in programming. Want to know a lot of other programming knowledge to solve programming problems. To learn a certain kind of development knowledge, we have a Java master here. C++/C Master, Windows/linux Master, Android/ios Master, please pay attention to my public number: Program Ape Interactive Alliance or coder_online, Daniel Online to provide you with services.

Save files for Android data

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.