Detailed Android file storage _android

Source: Internet
Author: User
Tags documentation

Summary

In fact, the operation of the Android file and the operation of Java in the PC environment is not the second, the reason why need to be explained separately because the Android system provides a different from the PC access to the file system root path of the API, while the application of a private file to do a unified management. Based on my experience, beginners in this section feel that it is easy to confuse both internal and external storage concepts.

In fact, the operation of the Android file and the operation of Java in the PC environment is not the second, the reason why need to be explained separately because the Android system provides a different from the PC access to the file system root path of the API, while the application of a private file to do a unified management. Based on my experience, beginners in this section feel that it is easy to confuse both internal and external storage concepts.

Relative path and absolute path

In Java, the relative path and absolute path are explained in this way, if you are familiar with this section the following gray text can be skipped:

An absolute path is the full path to the writing file, such as D:\java\Hello.java, which contains the full path D:\java of the file and the full name Hello.java of the file. Using this path, you can only find a file that does not create ambiguity. However, using an absolute path to represent a file is very restrictive and cannot run under different operating systems, because the expression of an absolute path exists differently under different operating systems.

A relative path is a partial path to a writing file, such as \test\hello.java, that contains only the partial path \test of the file and the full name Hello.java of the file, and part of the path refers to the subpath under the current path, such as the current program running under D:\ABC, The full path to the file is d:\abc\test. Using this form, you can more commonly represent the location of the file, so that the file path has a certain degree of flexibility.

When you run a program in an Eclipse project, the current path is the root directory of the project, for example, when the workspace is stored in D:\javaproject, and the current project name is Test, the current path is: D:\javaproject\Test. When you run a program under the console, the current path is the directory where the class file resides, and if the class file contains the package name, the current path is the package name at the top of the class file.

This is what Java does in most operating systems, and it's obvious that we should use relative paths as much as possible, but in Android, in fact, most of the cases we use are absolute paths. Why, then? Note that the relative path is the current path with the current project's path. But in Android we can't do anything in the directory where the project is located, because our project in normal Java is created on the server (PC is also a server), running on the server, we can certainly operate our own file directory on the server. But in Android development, our project is generally created in their own work of the computer, and running on the mobile phone, since APK has been running on the phone, the project has been deployed to the mobile phone, should be apk on the phone position to determine the relative path, but we seem to have no way to operate this path, Because APK is in the system directory, even if you can, there is no point in accessing the file in this directory, such as I write an album program, the picture must be placed in the external storage, and if I want to save some of the application settings data, I was placed in the internal storage of the information directory, So in fact, in Android file management, we're all working on absolute paths.

File class

Manipulating a file (read, write, create file, or directory) is done through the file class, which is exactly the same as in Java.

Internal Storage internal storage space

The so-called internal storage and external storage, refers to whether the phone is built-in. Cell phone's built-in storage space, called internal storage, it is a mobile phone once the factory can not be changed, it is also one of the hardware indicators of the mobile phone, usually the larger the cell phone built-in storage space means that the higher the price of mobile phones (many places call it the phone memory, but we do software to know that this is not accurate, Memory is the place where a hand is stored in a program, data, and instruction; This should be the memory of the phone's internal storage, not the memory in the strictest sense.

The internal storage space is very limited, so it is valuable, so we have to avoid the use of as far as possible, in addition, it is the system itself and the system application of the main data storage location, once the internal storage space is exhausted, the mobile phone can not use. So for the internal storage space, we should try to avoid using. The shared preferences mentioned above and the SQLite databases discussed below are also stored in the internal storage space.

Android itself is a Linux operating system, so its internal storage space, for applications and users is the "/data/data" directory. Compared with other (external storage), it has the advantages of stable, convenient storage, simple operation and more security (because it can control access rights). And its only drawback is that it is relatively limited, more valuable.

Although it is very easy to know the path of the program itself, all the application data paths are "/data/data/app-package-name/", all the data used by the program, such as the Libs library, Sharedpreferences are stored under this path. But we had better not use it, or do not refer directly to this path.

There are two main ways to use internal storage, one is file operation and the other is folder operation. Either way, the context provides the appropriate function to support, the use of the context is not only easy to operate, the most important thing is that the context will help us manage these files, but also to help us to control the access to files. First come to the system next in the context of the functions of File and folder operations.

A. Create a file and open it into a file output stream, you need to supply a string as the filename

FileOutputStream output = context.openoutputfile (filename, context.mode_private); 
Output.write (data);//Use output to write whatever, like 
Output.close ();

B. Similarly, if you want to open a file as input, you only need to provide a filename

FileInputStream input = context.openinputfile (filename); 
Input.read (); 
Input.close ();

C. List all the files that you have created

string[] files = context.filelist (); 
for (String file:files) { 
log.e (TAG, ' file is ' + file); 
}

D. Delete files, can be created to be able to delete, of course, will also provide a delete file interface, it is also very simple, only need to provide file name

if (context.deletefile (filename)) { 
log.e (TAG, "delete file" + filename + "sucessfully"); 
} else { 
log.e (TAG, "failed to delete file" + filename); 
}

E. Gets the path of the file created file that returns a file object for the operation path

File Filedir = Context.getfiledir (); 
LOG.E (TAG, "Filedir" + Filedir.getabsolutepath ();

F. Create a directory that requires incoming directory names that return a file object to the operation path

File Workdir = Context.getdir (dirname, context.mode_private); 
LOG.E (TAG, "Workdir" + Workdir.getabsolutepath ();

G. View created files as a file object, need to pass in a filename, and return a file object

File store = context.getfilestreampath (filename); 
LOG.E (TAG, "store" + store.length ());

H. Get cache path, no need to pass in parameters, return file object

File Cachedir = Context.getcachedir (); 
LOG.E (TAG, "Cachedir" + Cachedir.getabsolutepath ());

Summary of file-related operations , you can draw the following three features :

1. File operation only need to provide file name to the function, so the program itself only needs to maintain the filename;
2. Do not have to create the file object and input, output stream, provide file name can return the file object or input output stream

3. All returned to the path operation are file objects.

As mentioned earlier, the internal storage space is limited, valuable, secure, stable, so should be used to save more important data, such as user information, password secret code, etc. do not need to share data with other applications. can also be used to create temporary files, but be careful to delete them in time. In addition, there is a very important feature of internal storage, that is, when an application is unloaded, the file data for the application's internal storage space will be deleted. The reason the system does this is simply that because the internal storage is limited, it must be available, because once it is full, the system will no longer function properly.

External Storage External storage space

To talk about mobile phone external storage space, and the internal storage space, the external storage space refers to the mobile phone when the factory does not exist, users can be free to add in the use of external storage media such as TS Card, SD card, such as flash storage media. These flash media from the initial space of small price expensive, to the current high capacity price is cheap, so almost every support for external storage of mobile phones above have a large capacity (greater than 2G) of the flash card.

Android is no exception, and it fully supports external storage media. More precisely, it relies on external memory cards because, for Android, many system applications cannot be used without external memory cards, such as multimedia-related applications. Although Android is very dependent on, but the external memory card also has its own characteristics, its biggest advantage is that storage space is large, basically you can use unlimited, and do not worry about to clean up the data. For now, many programs are using an external memory card, but there are few programs to actively clean up the data, so no matter how big your SD card is, its free space is getting less. Unlike internal storage, when a program unloads, the file data that it creates on the external store is not purged. So the responsibility to clean up the external storage space to the user himself, every once in a while to check the SD card, found useless data immediately deleted. The disadvantage of external storage is not very stable, for the Android phone can say, very unstable, its own flash media is prone to problems, SD card in the state of normal use is very much.

To start with, external storage -related usage methods and APIs:

A check media availability check the availability of the media.

As mentioned earlier, the stability of external storage media is very poor, so you must check its availability before use, if you can use

Final String state = Environment.getexternalstoragestate (); 

B. Get the directory gets the path to the external storage card

In fact, the path to the external memory card is "/mnt/sdcard", so you can access it directly by writing to it. Given the readability and portability considerations, it is recommended to write this:

 File Sdcarddir = Environment.getexternalstoragedirectory ();

C. for API 8 or greater, there are some the other useful APIs helping to manager files and directories.

If you use API 8 (Android 2.2) or higher, the SDK has several more interfaces for external storage of files and paths, and the documentation also suggests that the starting user will use the SD card more standardized. For example, create the appropriate directory to store the corresponding data, music,picture,video and so on. The application directory has also become "/android/data/package-name/data". Specific use can refer to the documentation, which is not duplicated here. Of course, as with programming specifications, this is just a specification, and you can totally do it without it, but for readability and portability, it's recommended to follow the documentation.

Here's a summary of some and external storage features you should be aware of when using:

A. External storage cards are not available at any time, so be sure to check their availability before using them

B. Data stored on external storage cards is visible to all applications and visible to users (using FileManager), so security is not very good, although the document claims to be able to write private data on an external memory card, but it doesn't seem to work. You can still delete or edit files with FileManager (market FileManager features are powerful enough to allow users to see all the files in the SD card and to manipulate the files they can see).

C. Android phone support to mount the external storage card to the PC as a U disk, when connecting the data line, when the SD card into a U disk connected to another operating system. What that means is that while some of the file attributes (hidden, private, etc.) are on Android, it doesn't necessarily work on the PC, and users can manipulate the files on their PCs (which is the 2nd mentioned).

D. If you use an external memory card to save data, be sure to do extra processing: Where to store the data when the external memory card is unavailable, and how to synchronize the data when available (this is a more painful place, the practical approach is to not allow the user to write the data when the SD card is unavailable, but this user experience is not very good, but as you know, Many applications do so); Your data is corrupted. Of course, common anomalies to consider, such as full space, unable to write, Disk Bad road, and so on.
We can also look at the common file directories:

Don't forget the permission.

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


log.i (TAG, "getfilesdir =" + Getfilesdir ()); 
LOG.I (TAG, "getexternalfilesdir =" + Getexternalfilesdir ("Exter_test"). GetAbsolutePath ()); 
LOG.I (TAG, "getdownloadcachedirectory =" + environment.getdownloadcachedirectory (). GetAbsolutePath ()); 
LOG.I (TAG, "getdatadirectory =" + environment.getdatadirectory (). GetAbsolutePath ()); 
LOG.I (TAG, "getexternalstoragedirectory =" + environment.getexternalstoragedirectory (). GetAbsolutePath ()); 
LOG.I (TAG, "getexternalstoragepublicdirectory =" + environment.getexternalstoragepublicdirectory ("pub_test"));

The above content is relatively long, I hope you can be patient to read, this article is all the essence, about the knowledge of the Android file storage, please click this site to learn more.

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.