SP storage, internal storage and external storage of Android data storage

Time:2021-9-3

SP storage, internal storage and external storage of Android data storage

Android provides a variety of data storage technologies to permanently save application data, so that developers can choose the appropriate data storage scheme according to their own needs, mainly includingSharedPreferences,Internal storage(Internal Storage),External storage(External Storage),SQLite databaseNetwork storage, etc

1: SharedPreferences

Step 1: get the SharedPreferences object with the getsharedpreferences method. The system will display / data / package name / shared_ Generate a * * file in the prefs directory
SP storage, internal storage and external storage of Android data storage
Context.MODE_PRIVATE:Default file creation mode. Use this mode to create a file. If a file with the same name already exists in the file directory, the new file will overwrite the old file. Moreover, the file can only be accessed by the application that created the file (or the application that shares the same user ID with the application).
Context.MODE_APPEND:Use this mode to create a file. If a file with the same name already exists in the file directory, the new content will be added directly to the end of the old file, instead of creating a new file to overwrite the old file.
Context.MODE_WORLD_READABLE:Make other applications have read permission to the file.
Context.MODE_WORLD_WIRTEABLE:Make other applications have write permission to the file.
Note: modeorldreadable and modeorldwriteable have been deprecated since API level 17. Starting with Android n (i.e. 7. X), using these two constants will lead to SecurityException. This means that applications for Android N and later cannot share private files by name. Trying to share a URI of type “file: / /” will result in fileuriexposedexception.
Step 2: get a SharedPreferences. Editor object through the edit () method of the SharedPreferences object
Step 3: call putboolean() (or putstring(), putint(), depending on the data type of the data to be saved) and other methods to add values
SP storage, internal storage and external storage of Android data storage
Step 4: use the submit commit () method to have the return value boolean type and apply () has no return value

/*Get SharedPreferences object
1. The first parameter is name: which indicates the file name. The system will display it in / data / data / package name / shared_ Generate an. XML file named after this parameter in the prefs directory
2. The second mode represents the created mode. It is recommended to be 0 or mode_ PRIVATE
* */
SharedPreferences sp = getSharedPreferences("test_sp", MODE_PRIVATE);
//Get editor object
SharedPreferences.Editor editor = sp.edit();
//Call the corresponding put method according to the data type to be saved
//Add as key value pair
Editor.putstring ("data", "I'm Rocky");
//To submit a new value, you must execute it, otherwise the previous operation is invalid
editor.commit();

result:

<map>
 < string name = "data" > I'm rocky < / String >
</map>

Step 5: obtain SP data

//Get the SharedPreferences object according to the name attribute used when saving
SharedPreferences sp=getSharedPreferences("test_sp",MODE_PRIVATE);
//According to the data type, call the corresponding get method to obtain the corresponding value through the key.
String aa=sp.getString("data",null);
Log.d("aa",aa);
result:
D / AA: I'm rocky
2: Internal storage

Create private files for internal storage: file directory / data / data / package name / files
Write file test_ file

//File name
String file_name="test_file";
//Write content
String content="Hello Android!";
try {
    //Write out the data, take the program as the center, and write the data into the file
 FileOutputStream fos=openFileOutput(file_name,MODE_PRIVATE);
 //Call write to write data
 fos.write(content.getBytes());
 //Call close() to close the data flow
 fos.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

result:
Hello Android!

SP storage, internal storage and external storage of Android data storage
To read a file from internal storage, the steps are as follows:
1. Use the file name of the file to be read as a parameter, call the openfileinput () method, and return a FileInputStream instance.
2. Call the read () method to read the file bytes.
SP storage, internal storage and external storage of Android data storage
3. Convert byte array to string type
4. Call the close () method to close the streaming.

private FileInputStream fis;
//Byte array for storing data streams
byte[] bytes=new byte[1024];// The 1024 byte array is 1KB
int read=0;// Get the number of bytes read at the time, and return - 1 at the end of the read band;
try {
    //Call openfileinput and return a FileInputStream
 fis = openFileInput(file_name);
  //Cyclic reading
 while ((read= fis.read(bytes))!=- 1) {// read the information in FIS into the bytes array
        //// convert byte to string from 0 to read to string
 String s=new String(bytes,0,read);
 Log.d("s",s);
 }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}finally {
    try {
        fis.close();
 } catch (IOException e) {
        e.printStackTrace();
 }
}
result:
D/s: Hello Android!

Note: file reading and writing operations are time-consuming operations, so it is best not to execute them in the main thread (UI thread) to avoid anr (program does not respond). Also, after each operation, remember to call the close () method to close the corresponding input stream or output stream to release system resources.

3: Internal storage cache file

File directory: data / data / package name / cache
    When some files only need temporary use and do not need to be saved permanently, these files should be saved in the internally stored cache directory. Files saved in the internally stored cache directory. When the internal storage space of the device is insufficient, the system may first delete these cache files to free memory space. However, developers should not rely on the system to clean up these files, but should always maintain their own cache files to keep their occupied space within a reasonable limit (such as 1MB). When the application is unloaded, the cache file is also removed.

//File name
String file_cache_name="test_cache_file";
//Write content
String cache_content="Hello Cache World";
//Use the getcachedir () method to get the internal storage cache directory
File cacheDir=getCacheDir();// This is the cache directory structure
//Construction file path, / data / data / package name / cache / file name
//In this way, it indicates that the file is to be saved in the internal storage cache directory.
String cache_file=cacheDir+"/"+file_cache_name;
try {
    //It is passed in through the construction method of fileoutputstream
 //Returns a fileoutputstream instance.
 //Note: openfileoutput is no longer used here because
 //The path separator '/' is not allowed for the openfileoutput parameter,
 //If you continue to use the openfileoutput method, the
 //Illegalargumentexception exception
 FileOutputStream cache_fos=new FileOutputStream(cache_file);
 //Call the write () method to write data
 cache_fos.write(cache_content.getBytes());
 //Call close() to close the output stream
 cache_fos.close();
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}
result:
Hello Cache World

Read the cache file that internally stores the cache directory file

//File name
String file_cache_name="test_cache_file";
private FileInputStream inputStream;
//Byte array for storing data streams
byte[] bytes=new byte[1024];
int read=0;// Get the number of bytes read at the time, and return - 1 at the end of the read band;
try {
    File cache=getCacheDir();
 String cache_file=cache+"/"+file_cache_name;
 inputStream = new FileInputStream(cache_file);
 while ((read= inputStream.read(bytes))!=-1){
        //// convert byte to string from 0 to read to string
 String c=new String(bytes,0,read);
 Log.d("c",c);
 }
} catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}finally {
    try {
        inputStream.close();
 } catch (IOException e) {
        e.printStackTrace();
 }
}
result:
 D/c: Hello Cache World

A practical method for the operation of files and directories in internal storage
Getfilesdir(): get the absolute path of the file system directory where the internal files are stored. That is / data / data / package name / files
GETDIR (string name, int mode): create a new (or open an existing) directory in the internal storage space. That is, create (or open) an existing directory under the data / data / package name directory
Deletefile (string name): deletes the file specified by the name attribute in the / data / data / package name / files directory. This method parameter cannot contain the path separator “/”, just pass in the file name of the file to be deleted.
Filelist(): lists the file names of all files in the / data / package name / files directory.

4: External storage

All Android compatible devices support a shared external storage that allows users to save files. The external storage may be a portable storage medium (SD card), or a partition allocated by the system on its own internal memory for external storage. Including some public directories on the device, such as mobile photo albums (pictures), music (Music) and other directories. Files stored in external storage are global read-write files.
1. Access permissions need to be added for external storage. In the androidmanifest.xml file, android6.0 permissions need to be obtained dynamically

//Writable
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
//Readable
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />

2. Judge the status of the current equipment
Environment. Getexternalstoragestate() returns the current state of the external storage device
Environment. Getdatadirectory() returns file to get the root directory of data
Environment. Getrootdirectory() returns file to get the root directory of Android
D/aa: mounted
D/aa: /data
D/aa: /system
Environment.MEDIA_ Mounted equals “mounted”, which means SD card is mounted, readable and writable
Environment.MEDIA_ Unmounted is equal to “unmounted”. Media is unmounted and unreadable
etc.

//Get availability of external storage
String state=Environment.getExternalStorageState();
if (Environment.MEDIA_MOUNTED.equals(state)){
    return true;
}

3. Get the path of external storage album

File picDirectory2= getExternalFilesDir(Environment.DIRECTORY_PICTURES);
//Get the album directory of the device
File picDirectory =Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
Log.d("aa",picDirectory2.getAbsolutePath());
Log.d("aa",picDirectory.getAbsolutePath());
result:
D/aa: /storage/emulated/0/Android/data/com.ruan.testw/files/Pictures
D/aa: /storage/emulated/0/Pictures
//Gets the status of the external device
String state=Environment.getExternalStorageState();
//If peripherals can be used
if (Environment.MEDIA_MOUNTED.equals(state)){
    File picDirectory2= getExternalFilesDir(Environment.DIRECTORY_PICTURES);
 //Get the album directory of the device
 File picDirectory =Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
 Log.d("aa",picDirectory2.getAbsolutePath());
 Log.d("aa",picDirectory.getAbsolutePath());
 File file=new File(picDirectory2,"My_ pic");// The first parameter is the parent file, and the second file is the child file
 if (! File. Exists()) {// if the file does not exist, create a new file
 try {
            file.createNewFile();
 } catch (IOException e) {
            e.printStackTrace();
 }
    }
File picDirectory3= getExternalCacheDir();
Log.d("aa",picDirectory3.getAbsolutePath());
result:
D/aa: /storage/emulated/0/Android/data/com.ruan.testw/cache
//Gets the status of the external device
String state=Environment.getExternalStorageState();
String cont = "I am in an external storage file";
//If peripherals can be used
if (Environment.MEDIA_MOUNTED.equals(state)){
    String file_path=Environment.getExternalStorageDirectory().getAbsolutePath();
    Log.d("aa",file_path);
    }
File file=new File(file_path+"/"+"My_Test");
if (!file.exists()){
        file.mkdir();// create folder
}else {
    FileOutputStream fileOutputStream= null;
 try {
        File file1=new File(file,"wo");
 fileOutputStream = new FileOutputStream(file1);
 fileOutputStream.write(cont.getBytes());
 fileOutputStream.flush();
 fileOutputStream.close();
 } catch (FileNotFoundException e) {
        e.printStackTrace();
 } catch (IOException e) {
        e.printStackTrace();
 }
}
result:
Write content to D / AA: / storage / emulated / 0 / my_ Under test / Wo file
I'm in an external storage file

Summary:
1. Environment. Getexternalstoragedirectory() get the directory of external storage
/storage/emulated/0
2. Environment. Getrootdirectory() gets the system directory of the storage system
/system
3. Environment. Getdatadirectory() get the data directory
/data
4. Environment. Getdownloadcachedirectory() get the data directory
/data/cache
5. Getexternalcachedir() / / get the cache under the external storage package name
/storage/emulated/0/Android/data/com.ruan.testw/cache
6. Getcachedir() get the cache under internal storage
/data/data/com.ruan.testw/cache
7. Getfilesdir() get the files under internal storage
/data/user/0/com.ruan.testw/files=/data/data/com.ruan.testw/files
8.getExternalFilesDir(Environment.DIRECTORY_ DCIM) obtain the files under the package name stored externally. / / the parameter is a string of “AA”
/storage/emulated/0/Android/data/com.ruan.testw/files/DCIM
9.getSharedPreferences(“test_ sp”, MODE_ PRIVATE); Get SharedPreferences object
/Data / data / package name / shared_ prefs/test_ sp
END:
In the eyes of the strong, there is no best, only better

Recommended Today

Java Engineer Interview Questions

The content covers: Java, mybatis, zookeeper, Dubbo, elasticsearch, memcached, redis, mysql, spring, spring boot, springcloud, rabbitmq, Kafka, Linux, etcMybatis interview questions1. What is mybatis?1. Mybatis is a semi ORM (object relational mapping) framework. It encapsulates JDBC internally. During development, you only need to pay attention to the SQL statement itself, and you don’t need to […]