"Go" file operation details in Android as well as internal storage and external storage

Source: Internet
Author: User

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

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

Relative path and absolute path

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

An absolute path is the full path to a written file, such as D:\java\Hello.java, which contains the full path of the file D:\java and the full name of the file Hello.java. Using this path, you can find only one file without ambiguity. However, the use of absolute paths in representing files is very restrictive and cannot be run under different operating systems because absolute paths are expressed differently under different operating systems.

A relative path is a partial path to a written file, such as \test\hello.java, which contains only part of the path to the file \test and the full name of the file Hello.java, some of which are sub-paths under the current path, such as the current program running under D:\ABC. Then the full path to the file is d:\abc\test. Using this form, you can more generally represent the location of the file, resulting in a certain degree of flexibility in the file path.

When you run a program in an Eclipse project, the current path is the root of the project, such as when the workspace is stored in D:\javaproject and the current project name is Test, the current path is: D:\javaproject\Test. When running 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 package name at the top of the class file is the current path.

This is what Java does in most operating systems, and it is clear that we use relative paths as much as possible, but in Android, in most cases we are using absolute paths. Why is it? Note that the relative path is the current path as the current project, but in Android we are not able to do anything in the path directory of the project, because ordinary Java our project is created in the server (PC is a server), running on the server, we can of course, the server operating its own file directory. But Android development, our project is generally created in their own work of the computer, and running on the mobile phone, since the APK has been running on the phone, the project has been deployed to the mobile phone, should be in the location of the APK on the phone to determine the relative path, but we seem to have no way to operate this path, Because the APK is in the system directory, even if it can be manipulated, access to files in this directory is meaningless, such as I write a photo album program, the picture must be placed in the external storage, and if I want to save some of the app's settings data, I was placed in the internal storage of the database directory, So in fact, in the Android file management, we are operating the absolute path.

File class

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

External storage External storage and internal storage Internal storage

1. Internal storage:

Note Internal storage is not memory. Internal storage is a very special location in the system, and if you want to store the files in an internal store, the files are only accessible to your app by default, and all files created by an app are in the same directory as the app package name. This means that the application is created in the internal storage file, which is associated with the application. When an app is uninstalled, these files in the internal storage are also deleted. Technically, if you set the file property to be readable when you create the internal storage file, other apps can access your app's data, provided that he knows the package name of your app, and if the property of a file is private, then even if you know the package name, other apps won't be able to access it. The internal storage space is very limited, so it is valuable, 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 phone will not be used. So for the internal storage space, we should try to avoid it. Shared preferences and SQLite databases are stored on the internal storage space. Internal storage is generally used to obtain and manipulate the context.

Getfilesdir () Gets the internal storage space of your app, which is the root of your app's internal storage.

If you are creating a file, the following

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

Android also provides us with an easy way to   openfileoutput () to read and write files that are applied to the internal storage space, here is an example of writing text to a file:

12345678910 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();}

Some additional operations for internal storage:

A. List all the files that have been created, which may not be easy to imagine, Context actually have such a method.

1234 String[] files = Context.fileList();for(String file : files) {Log.e(TAG, "file is "+ file);}

B. Delete files, can be created to be able to delete, of course, also provides the interface to delete files, it is very simple, only need to provide file name

12345 if(Context.deleteFile(filename)) {Log.e(TAG, "delete file "+ filename + " sucessfully“);} else {Log.e(TAG, "failed to deletefile " + filename);}

C. Create a directory, you need to pass in the directory name, it returns a file object to the action path

12 File workDir = Context.getDir(dirName, Context.MODE_PRIVATE);Log.e(TAG, "workdir "+ workDir.getAbsolutePath();


Summarize the file related operations, you can draw the following three features:
1. File operation only need to provide a file name to the function, so the program itself only needs to maintain the file name;
2. No need to create file object and input, output stream, provide file name can return file object or input output stream
3. The file object is returned for the path operation.

2. External storage:

The most confusing is the external storage, if the PC is also to distinguish between external storage and internal storage, then the drive is internal storage, U disk or mobile hard disk is external storage, so we can easily take this understanding to look at the Android phone, think that the intrinsic storage of the fuselage is internal storage, The extended t card is external storage. For example, our 16GB version of Nexus 4 has 16G of internal storage, ordinary consumers can understand this, but Android programming can not, this 16GB is still external storage.

All Android devices have external storage and internal storage, both of which are from the early devices of Android, where the device's internal storage is really fixed, and the external storage can be moved like a USB stick. But in later devices, many medium-and high-end machines have extended their own body storage to more than 8G, they will be stored in the concept of "internal internal" and "external external" two parts, but in fact, are inside the phone. So regardless of whether Android phones have removable sdcard, they always have external storage and internal storage. Most crucially, we all use the same API to access removable sdcard or the storage that comes with the phone (external storage).

Although the concept of external storage is a little complicated, but also very good to distinguish, you connect your phone to the computer, the computer can be recognized by the part of the external storage must be.

With regard to external storage, I think the API is very clear when introducing the Environment.getexternalstoragedirectory () method:

Don ' t be confused by the word "external" here. This directory can better is thought as media/shared storage. It is a filesystem so can hold a relatively large amount of the data and that's shared across all applications (does not en Force permissions). Traditionally this was an SD card, but it could also be implemented as built-in storage in a device which is distinct from the Protected internal storage and can is mounted as a filesystem on a computer.

Do not understand, in fact, and I said the meaning of almost, just think that the comparison of image, do not know is my expression problem, or English in the logical interpretation of the strong than Chinese, because the vernacular is actually castrated Chinese.

Files in external storage can be modified by users or other applications, and there are two types of files (or directories):

1. Public file Common Files: Files can be accessed freely, and the data of the file is meaningful to other applications or users, and the files created before uninstallation are retained when the application is uninstalled. For example, the camera app, the generated photos can be accessed by everyone, and the camera is gone, the photos are still there.

If you want to put public files on the external storage you can use getexternalstoragepublicdirectory ()

123456789 public File 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");}returnfile;}

In the above code we create a directory where the picture is stored and create a new Albumname file.

If your API version is less than 8, you cannot use getexternalstoragepublicdirectory (), but instead use Environment . getExternalStorageDirectory (), which he does not have parameters, You cannot create a directory on your own, just return the root path of the external store.

2. Private file: In fact, because it is external storage is the reason that this type of file can also be accessed by other programs, but an application of private files for other applications is actually no access value (except for malicious programs). On external storage, the value of applying a private file is that the files are deleted after they are uninstalled. Similar to internal storage.

The way to create an app private file isContext.getExternalFilesDir(),如下:

123456789 public File getalbumstoragedir (context context, String Albumname) { //Get the directory for the app ' s private pictures directory. file File = NewFile (Context.getexternalfilesdir ( if (!file.mkdirs ()) { log.e (log_tag,  " Directory not created " ); returnfile;

The above code creates a picture directory and creates a file named in this directory albumName , which Environment.DIRECTORY_PICTURES is actually the string picture.

The private files stored externally for all applications are placed under the android/data/of the root directory, in the form of/android/data/<package_name>/

If your API version is less than 8, then you getExternalFilesDir() cannot use it, but use the Environment . getExternalStorageDirectory () to get the root path and try to manipulate it yourself/android/data/ <package_name>/Under the file.

In other words, the following versions of API 8 do not provide API support specifically for the operation of files and private files. You can only get the root directory and then do it yourself.

Before using external storage, you must first check the current state of the external storage to determine if it is available.

123456789101112131415 boolean mExternalStorageAvailable = false;boolean mExternalStorageWriteable = false;String state = Environment.getExternalStorageState();if(Environment.MEDIA_MOUNTED.equals(state)) {// We can read and write the mediamExternalStorageAvailable = mExternalStorageWriteable = true;} elseif(Environment.MEDIA_MOUNTED_READ_ONLY.equals(state)) {// We can only read the mediamExternalStorageAvailable = true;mExternalStorageWriteable = false;else{// Something else is wrong. It may be one of many other states, but all we need//  to know is we can neither read nor writemExternalStorageAvailable = mExternalStorageWriteable = false;}

Finally, in order to clarify the getfilesdir,getexternalfilesdir,getexternalstoragedirectory, Getexternalstoragepublicdirectory and other Android file operation methods, I will print out the results of these methods to see exactly what the path is, execute the following code in the activity:

123456 Log.i("codecraeer""getFilesDir = "+ getFilesDir());Log.i("codecraeer""getExternalFilesDir = "+ getExternalFilesDir("exter_test").getAbsolutePath());Log.i("codecraeer""getDownloadCacheDirectory = "+ Environment.getDownloadCacheDirectory().getAbsolutePath());Log.i("codecraeer""getDataDirectory = "+ Environment.getDataDirectory().getAbsolutePath());Log.i("codecraeer""getExternalStorageDirectory = "+ Environment.getExternalStorageDirectory().getAbsolutePath());Log.i("codecraeer""getExternalStoragePublicDirectory = "+ Environment.getExternalStoragePublicDirectory("pub_test"));

See the following results in log:

From the log we can see that the external storage root is/storage/emulated/0 on my phone (Nexus 3), and oddly enough on some phones the same code is the following:

The/mnt/sdcard storage root directory.

Search on the Internet as if to say that Samsung mobile phone is like this.

Reference article: Http://developer.android.com/training/basics/data-storage/files.html#InternalVsExternalStorage

Http://developer.android.com/guide/topics/data/data-storage.html

from:http://blog.csdn.net/androidwifi/article/details/17725989/

"Go" file operation details in Android as well as internal storage and external storage

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.