During the development of Android, we often need to store files, so we should also tidy up the relevant knowledge in this area, to maintain files on the user’s device, but also need to know the difference between internal storage and external storage.

This text mind map

First take a look at our mind map for this chapter, hoping to help you understand the knowledge points in this article in a straightforward and profound way in a fragmented or short time.

Internal storage

Whether user rights are required: No

Can be accessed by other applications: No

Uninstallation Whether application data is deleted: Yes

Internal storage controls do not require user permissions, This means that we don’t need the user to authorize android.permission.WRITE_EXTERNAL_STORAGE and android.permission.READ_EXTERNAL_STORAGE to read and write files in this directory. Files in this directory cannot be accessed by other applications. This ensures the security and privacy of the files stored inside our app. If we need to view the files inside our app, we can access them through Android Studio’s Device File Explore tool:

We can access /data/data/ application package name to view the internal storage files under our application.

/data/data/ application name /cache: stores APP cache information

/data/data/ application name /code_cache: Stores compiled or optimized code generated by the application at runtime

/data/data/ application name /files: stores APP file information

There are also some runtime folders, such as /data/data/ application package name /shared_prefs directory generated by calling SharedPreference, which contains XML files generated by app SharedPreference. **/data/data/ application package name/Databases /** folder.

The relevant API

getCacheDir

File getCacheDir() returns the cache folder for internal storage

Log.d("DaMai",getCacheDir().getPath()); //data/user/0/com.example.vicky.yinji/cache
Copy the code

getCodeCacheDir

File getCodeCacheDir() returns the internal stored code_cache folder, required by Android5.0+

Log.d("DaMai",getCodeCacheDir().getPath()); ///data/user/0/com.example.vicky.yinji/code_cache
Copy the code

getFilesDir

File getFilesDir() accesses the files directory of internal storage

Log.d("DaMai",getFilesDir().getPath()); ///data/user/0/com.example.vicky.yinji/files
Copy the code

fileList

String[] fileList() Returns the names of files. For example, there are test.txt and test1.txt files in the files directory

    // Output test.txt and test1.txt
    for (String item : fileList()){
            Log.d("DaMai",item);
    }
Copy the code

openFileOutput

FileOutputStream openFileOutput() Writes files to the files directory:

    try {
        FileOutputStream outputStream = openFileOutput("test.txt", Context.MODE_PRIVATE);
        outputStream.write("this is test content".getBytes());
        outputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
Copy the code

The test.txt file will be added to the file directory

openFileInput

FileInputStream openFileInput() Reads files in the files directory. For example, we read the test.txt file we just wrote

    // Output: This is test content
    try {
        FileInputStream fileInputStream = openFileInput("test.txt");
        byte[] bytes = new byte[1024];
        StringBuffer stringBuffer = new StringBuffer();
        int len = 0;
        while((len=fileInputStream.read(bytes))! = -1){
            stringBuffer.append(new String(bytes,0,len));
        }
        Log.d("DaMai",stringBuffer.toString());
        fileInputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
Copy the code

getDataDir

File getDataDir() returns internal storage to the root folder, required by Android7.0+

    Log.d("DaMai",getDataDir().getPath()); ///data/user/0/com.example.vicky.yinji
Copy the code

External storage

Public directory

Whether user rights are required: Yes

Can be accessed by other applications? Yes

Uninstallation Whether application data is deleted: No

The public directory must require user permissions to read and write, which means we need to register user permissions in androidmanifest.xml.

    <! Write data to SDCard -->
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
Copy the code

And after Android 6.0 system need to apply for user permission, and obtain user authorization, to read and write files.

The public directory is relatively open. We can access the files in the public directory of other apps. When the APP is deleted, the files in the public directory of the APP will not be deleted.

We can access and read files in public directories through the Environment object. Let’s take a look at the API.

The relevant API

Environment.getExternalStorageDirectory

File Environment. External.getexternalstoragedirectory () public access external storage root directory:

    // Output: /storage/emulated/0
    Log.d("DaMai",Environment.getExternalStorageDirectory().getPath()); 
Copy the code
Environment.getExternalStoragePublicDirectory

File Environment.getExternalStoragePublicDirectory(String type)

We can use type to access the corresponding files in the public directory, for example:

    Output: / / / storage/emulated / 0 / Music
    Log.d("DaMai",Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC).getPath());
Copy the code

The Environment object provides us with rich access to the types in the corresponding public directory. We can view them through the source code of the Environment object, which is not described here.

Environment.getExternalStorageState

String Environment. GetExternalStorageState () to obtain external storage state of SD card, read and write in the SD card, we should assess the state of SD card, will be able to support reading and writing.

The return value and the corresponding state can also see the Environment. The getExternalStorageState source.

Private directory

Whether user rights are required: 4.4 No user rights are required

Can be accessed by other applications: No

Uninstallation Whether application data is deleted: Yes

Private directory, above Android4.4. Files can be read and written in the private directory of the application without registration or user authorization for SD read and write. In addition, files cannot be accessed by other applications, ensuring high privacy and security. When a user deletes a file, the corresponding private application directory will also be deleted.

Address: private directory/storage/emulated / 0 / Android/data/application package name

The relevant API

The API accessed from the private directory is on the ContextWrapper object. This means that we can call it directly from the Activity or from the Context object.

getExternalCacheDir

File Context. GetExternalCacheDir () access/storage/emulated / 0 / Android/data/packages/cache directory, cache files used by the directory to store application, when we are through application to delete cache File, Files in this directory will be deleted.

    Output: / / / storage/emulated / 0 / Android/data/com. Example. Vicky. Yinji/cache
    Log.d("DaMai".this.getExternalCacheDir().getPath());
Copy the code
getExternalFilesDir

The File Context. GetExternalFilesDir (String type) access/storage/emulated / 0 / Android/data/packages/files directory, the directory used to store application data, Files in this directory will be deleted when we delete application data from the application. We can also use type to create and obtain the File in the corresponding directory. Such as:

    Create and output: / / / storage/emulated / 0 / Android/data/com. Example. Vicky. Yinji/files/test
    Log.d("DaMai".this.getExternalFilesDir("test").getPath());
Copy the code

We can also pass type to null and access the files directory, for example:

    Output: / / / storage/emulated / 0 / Android/data/com. Example. Vicky. Yinji/files
    Log.d("DaMai".this.getExternalFilesDir(null).getPath());
Copy the code

analyse

We often carry out file storage in the development, this time we finally figure out the Android file storage, when we need to store some privacy and security relatively high small data, such as user account password information, we can store in the internal storage space; When we need to store some data that can be accessed by other applications, and when the application is deleted, we can put the data in the public directory of external storage, but don’t forget to apply for read and write SD card permission oh; If you need to store some application data and cache data to ensure privacy and delete the application data, you can choose to store the application data and cache data in the private directory of external storage.

I am Damai, if you like my article, please give me a careful heart.