Android study note 34: Use files to store data

Source: Internet
Author: User

Android provides five data storage methods:

(1) files: Use fileinputstream and fileoutputstream to operate files.

(2) shared preferences: used to store data in the form of key-value pairs and save system configuration information.

(3) content providers: data sharing for ApplicationsProgramData access.

(4) SQLite: a lightweight relational database built in Android that supports the SQL language. It is used to store a large amount of data and can be used, updated, maintained, and operated on the data.

(5) Network: stores and obtains data through the network.

This blog article mainly introduces the first method to store data through files.

In Android, the file used to save data can be located in two locations: the storage space of the device or the external storage device (SD card ). This file cannot be shared by different applications by default no matter where it is stored.

The following describes how to store files in the storage space of the device and external storage devices.

 

1. store files in the storage space of the device.

In Android, you can use the following two methods provided by the context class to implement file storage.

(1) Public abstract fileinputstream openfileinput (string name); // open the file input stream

(2) public abstract fileoutstream openfileoutput (string name, int mode); // open the file output stream

The openfileinput () method indicates that the file input stream is opened and used to read data from the file. The openfileoutput () method indicates that the file output stream is opened and used to write content to the file.

In addition, the second parameter mode in the openfileoutput () method is used to specify the file operation mode. The optional values include:

(1) Context. mode_append ;//Content appending mode. In this mode, the system checks whether the file exists. If yes, the content is appended to the end of the file. If the file does not exist, the file is created and written to the content.

(2) Context. mode_private ;//Default operation mode. In this mode, files are private data and can only be accessed by the application itself. In this mode, the written content overwrites the content of the original file.

(3) Context. mode_world_readable ;//Read mode. In this mode, other applications can read the file content.

(4) Context. mode_world_writeable ;//Writable mode. In this mode, other applications can write content to the file.

1.1 storage files

An example of a simple file storage is as follows:

 1  /* 2   * Function: Save the file to the local memory.  3   * Author: blog Park-still indifferent  4        */  5       Public   Void Savecontenttolocal (string filenmae, string content) Throws  Ioexception {  6 Fileoutputstream = Mcontext. openfileoutput (filenmae, context. mode_append ); 7   Fileoutputstream. Write (content. getbytes ());  8           If (Fileoutputstream! = Null  ){  9   Fileoutputstream. Close ();  10   }  11 }

The aboveCodeBy setting the second parameter of openfileoutput () to mode_append, the file is stored in content append mode.

1.2 monomer Test

How can we verify the correctness of the above Code? We can quickly verify the above Code by creating a standalone test.

The specific standalone test code is as follows:

 1       /*  2   * Function: test the function of saving a file to a local device.  3   * Author: blog Park-still indifferent  4        */  5       Public   Void Savefiletolocal () Throws  Ioexception { 6 Context cotext = Getcontext ();  7 Fileservice = New  Fileservice (cotext );  8 Fileservice. savecontenttolocal ("test.txt", "blog garden-still indifferent" );  9 }

After running the standalone test, we created a text file named "blog test.txt" in the notebook, whose content is "blog garden-still indifferent ".

Where is the file stored? In fact, every time an application is installed, a folder is generated under the Data/data directory to save the data of the application. 1.

Figure 1 files stores data to a local file directory

It can be seen that the file is stored in the directory data/COM. example. android_datastorage_files/files, where com. example. android_datastorage_files is the package name of the project. Export the “test.txt text file and open it to see that the content is indeed "blog garden-still indifferent ".

1.3 read files

So how can we read the file in the program? The following code provides an implementation scheme.

 1       /*  2   * Function: reads files from the local memory.  3   * Author: blog Park-still indifferent  4        */ 5       Public String getfilefromlocal (string filenmae) Throws  Ioexception {  6           7 Fileinputstream = Mcontext. openfileinput (filenmae );  8           9           //  Creates a bytearrayoutputstream object to save data in the fileinputstream object.  10 Bytearrayoutputstream = New Bytearrayoutputstream ();  11           12           //  Read and Write the content of the fileinputstream object cyclically and save it to the bytearrayoutputstream object.  13           Int Len = 0 ;  14           Byte [] DATA = New   Byte [1024 ];  15           While (LEN = fileinputstream. Read (data ))! =-1){  16 Bytearrayoutputstream. Write (data, 0 , Len );  17   }  18           19           If (Fileinputstream! = Null ){ //  Disable fileinputstream object  20   Fileinputstream. Close ();  21  }  22           23           Return   New  String (bytearrayoutputstream. tobytearray ());  24 }

Similarly, we can create a standalone test to quickly verify its correctness. The specific method is similar to the previous test, so I will not go into details here.

 

2. store files in external storage devices (SD card)

Generally, the memory of a mobile phone is extremely limited. A more common practice is to store files in the SD card.

The method for storing files on an external storage device is similar to that for storing files in the storage space of the device itself. The only difference is that each time a file is stored on the SD card and read from the SD card, you must check the SD card status.

2.1 check the SD card status

In Android, the Environment class must be used to check the SD card status. You can use the getexternalstoragestate () method of this class to obtain the status of the external storage device (SD card. There are nine statuses of external storage devices, as shown in figure 2.


Figure 2 external storage device status

Media_mounted indicates that the external storage device is readable and writable.

2.2 storage files

A simple example of storing a file on the SD card is as follows:

 1  /*  2   * Function: Save the file to the SD card.  3   * Author: blog Park-still indifferent 4        */  5       Public   Boolean Savecontenttosdcard (string filenmae, string content) Throws  Ioexception {  6           7           Boolean Isexternalstorageavailable = False ; //  SD card read/write flag  8 Fileoutputstream =Null ; //  Fileoutputstream object  9           10           //  Create a file object and use the path of the SD card as the file storage path  11 File file = New  File (environment. getexternalstoragedirectory (), filenmae );  12           13           //  Determine whether the SD card can be read and written  14          If  (Environment. media_mounted.equals (environment. getexternalstoragestate ())){  15 Isexternalstorageavailable = True  ;  16 Fileoutputstream = New Fileoutputstream (File ); //  Create a fileoutputstream object  17 Fileoutputstream. Write (content. getbytes ()); //  Write Data to the fileoutputstream object 18               If (Fileoutputstream! = Null ){ //  Disable a fileoutputstream object  19   Fileoutputstream. Close ();  20   }  21   }  22           Return  Isexternalstorageavailable;  23 }

The environment. getexternalstoragedirectory () method is used to obtain the path of the SD card. When creating a file object, specify its storage path as the path of the SD card, which can store the file to the SD card.

2.3 monomer Test

Similarly, we create a standalone test to verify the above Code.

The specific standalone test code is as follows:

 1       /*  2   * Function: test the function of saving a file to the SD card.  3   * Author: blog Park-still indifferent  4        */  5      Public   Void Savefiletosdcard () Throws  Ioexception {  6 Context cotext = Getcontext ();  7 Fileservice = New  Fileservice (cotext );  8           Boolean Flag = fileservice. savecontenttosdcard ("hello.txt", "blog garden-still indifferent" );  9 Log. I (TAG, "flag -->" +Flag );  10 }

By running the standalone test, we can create a text file named "“hello.txt" in the SDK card with the content "blog garden-still indifferent ".

So where is the file stored? The answer is in the MNT/sdcard directory, as shown in 3.

Figure 3 storing data in files directory on the SD card

2.4 read files

Reading files from the SD card is similar to reading files from the local memory.

It must be noted that, because the program uses the read/write SD card, you need to add the permission to write data to the SD card and the permission to create and delete files on the SD card in the androidmanifest. xml file. The specific implementation method is as follows:

  1   
     permission to write data to the SD card   -->   2     uses-Permission   Android: name   = "android. permission. write_external_storage " />   3   
      permissions for creating and deleting files on the SD card   -->   4     uses-Permission   Android: name   = "android. permission. mount_unmount_filesystems " />  

 

3. instance (Notepad)

After learning how to store and read files in Android, we can implement a simple notepad application.

By using this notepad, you can enter the file name and content, and click "save file" to save the file content to the SD card, as shown in figure 4.

Figure 4 save an object

To read a file, click "Read File. In this case, the file content is read from the corresponding file in the SD card and displayed. 5.

Figure 5 File Reading

Of course, this instance only provides a way to use the method of storing and reading files to implement notepad. There are still many improvements to the instance itself.

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.