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 the image from the network to local as the cache data, and the number is large, sharedpreferences can not meet your needs, this time will be used 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, when most devices provide 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 space is very large, such as 16g or 32g, where 16g and 32g refers to the total size of the disk, the equivalent of your newly-bought computer a new hard disk. When the phone comes out of the factory, it will burn Android on this disk, the Android system will partition the entire disk, part of the Android system can be used to store system files, similar to the Windows system disk, but more than the permissions on Windows more stringent, The user is not free to access this part of the file (except root), this part is called internal storage, the rest of the users are free to use, the phone connected to the computer when you see the only part of the file, called external storage, equivalent to other disks on Windows (such as D disk), Of course, some users add a MICRO-SD card, which is also considered as external storage, the equivalent of Windows on the external hard disk bar.
There is a difference between internal storage and external storage, and it is important to pay attention to their respective features when used:
Internal storage:
    • There is always a usable;
    • The saved file can only be accessed by the app that saved the file, and the apps cannot access each other, only the files you saved.
    • When the application is uninstalled, the file saved will be completely erased;
    • If the file you want to save is safe and will not be read by users and other apps, then you can choose to store it internally.
External storage:
    • Not necessarily exist, for example, some mobile phone factory is only internal storage, no external storage, the user did not install 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;
    • When uninstalling an app, only the directory files obtained through Getexternalfilesdir () are deleted;
    • If your files do not need to control access, you can allow other applications or users to view, then the external storage is a good choice;

Note: By default the application installs to internal storage, you can specify the Android:installlocation property in the Androidmanifest.xml file so that your application can be installed on the external storage. This installation option is very useful for users, and when some applications are very large and the internal storage space is low, users can install the app to an external storage space.


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 following code:
<manifest ...> <uses-permissionandroid:name= "Android.permission.WRITE_EXTERNAL_STORAGE"/> ... </ Manifest>

Note: All applications now have read access to external storage by default. You do not need to declare in the Androidmanifest.xml file, but this default permission may be changed in later versions of Android, so it is better to make explicit Read permission declaration in androidmanifest, lest the program will have problems in a later version, the Read permission declaration is as follows:

<manifest ...> <uses-permissionandroid:name= "Android.permission.READ_EXTERNAL_STORAGE"/> ... </ Manifest>
In addition: 1, write permission implies Read permission, 2, the 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 needs to create files, when saving files to internal storage you can get the internal storage files through the following two methods:

1, File getfilesdir ();

returns a file directory in which the data for the application is saved, and the files created by Openfileoutput (String, int) are saved in this directory. This directory is probably: data/data/package name/files, such as the Pea pod application is: data/data/com.wandoujia.phoenix2/files/
2, File getcachedir ();
returns a directory of files that are stored in the application cache file, which is first deleted when the system is running out of space. This directory is probably: data/data/package name/cache, such as Pea pod application is: data/data/com.wandoujia.phoenix2/cache/ Note: The deletion of the cache file should not rely on the system to delete it, The best way to do this is to set a maximum value for your app cache, such as 1M, and 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 storage, first to create a file, you can pass the file's constructor, the above two methods obtained by the path as parameters, it is convenient to create a file, for example:

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

Then create a file stream from the above file, write to the files, of course you may prefer the following way, by calling Openfileoutput () to create a fileoutputstream, 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 do this in the following way:

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

Or, you would prefer to create a temporary file in the cache directory using 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: In general, your application's internal storage files are not accessible to other applications, because access to other programs first needs to know the package name and file name of your app, and next you need to get access to your file. Technically, if you keep the file open for file read permissions, other applications can read, unless you set the file to read-write, or else the program cannot read your files, so the file permissions context.mode_private must be set.


Save to external storage: Save to external storage first check that the external storage exists and there is space left, because the external storage may be unplugged, or is connected to the computer, so when you want to save the file in the external storage of the first step is to check whether the external storage is hanging, You can see if the external storage is mounted by calling the Getexternalstoragestate () method, and if the return status is environment.media_mounted, it is already hanging and can be read and written. For example, the following code:
/* Checks if external storage is available for read and write */publicboolean Isext Ernalstoragewritable () {    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;} 
Although externally stored files can be accessed by users and other programs, you need to treat externally stored files in two categories: Public files: This type of file is fully developed, accessible to other applications or users, and will not be deleted when your app is uninstalled. For example, your photo process, users take photos will not be removed because the user uninstalled the application and delete photos, as well as watching video software, the user downloaded the video can not be removed because of the uninstall of two.
Private files: This type of file is proprietary to your application, is not available to other applications, and does not use any value, 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, or it will create a waste of user space, such as some cache files, map resources and so on.
If you want to save a common file to an external store, you can do so via Environment.java: public static, File Getexternalstoragepublicdirectory (String type) Method gets the public directory for external storage, there are several types of public directories, and depending on the type you enter, different folders are returned, type types are:
public static String Directory_alarms Standard Ringtone Catalogue
public static String Directory_dcim Storage directory for camera photo or video files
public static String Directory_downloads Download catalogue
public static String Directory_movies Movie Catalogue
public static String Directory_music Music catalogue
public static String Directory_notifications Cue tone catalogue
public static String Directory_pictures Picture Catalogue
public static String Directory_podcasts Podcast Catalogue
public static String Directory_ringtones Ringtone Directory

The most common Directory_pictures directory for everyone is:/mnt/sdcard/pictures, for example, if you want to store a picture, create a picture file in a public directory 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;

If you want to save private types of data to external storage, you can call Context.java by calling:

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 is an example of creating a private image 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;

If you do not have the type you need, you can enter NULL, which returns the root of the private directory of your application's external storage directory.

Note: Files created by the Getexternalfilesdir (string type) method are purged by the system when the user clears the data or when the application unloads, Getexternalstoragepublicdirectory (string The file created by the type method is not. In addition, regardless of which method you use to create the application external storage file, note the type of correctness, so that the system processing can be handled correctly, such as you save a file 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:
If you know the size of the file you want to save in advance, you can use the File.getfreespace () or File.gettotalspace () method to estimate whether the storage space can fit, This avoids ioexception when there is not enough storage space available. However, sometimes the available space through File.getfreespace () is not necessarily so much for you to use, if the size obtained by File.getfreespace () is a few m larger than your file 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: Before you save the file, you do not need to check the free space, but instead capture the ioexception when writing to the file, using this method instead of checking the size of the space, if you do not 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. If the file is stored on an internal store, 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, all files stored in the internal storage, 2, all stored in the Getexternalfilesdir () directory of external storage files;
Note: You need to regularly 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 of the store, according to the openness and the availability of the application are classified into private type and public type, as well as the method of file preservation and some considerations, Netizens have any doubts please leave a message or reply to my public number: Coder_online.

If you are interested in programming, want to know more programming knowledge, solve programming problems, want to learn a certain kind of development knowledge, we have Java master, c++/c Master, Windows/linux Master, Android/ios Master, Please pay attention to my public number: Programmer Interactive Alliance or Coder_online, Daniel Online to provide you with services.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

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.