What does data persistence mean?
Data persistence means that the instantaneous data in memory is saved to the storage device, and the device can be native, database, etc. The Android system offers three ways to simply implement data persistence, namely file storage, Sharedpreference storage, and database storage.
Persistent operations
- File storage
(1) Writing files
A Openfileoutput () method is provided in the Context class that returns a FileOutputStream object. This method receives 2 parameters, the first parameter is the file name, where the file name cannot include the path , all the files in Android are stored in the/data/data/<packagename>/files/directory by default, and the second parameter is the mode of operation of the file, there are 2 main kinds, mode_private and mode_append,mode_private are the default mode, the content written will overwrite the contents of the source file directly; If the file already exists in Mode_append mode, the file is appended directly to the file, and no files are created.
To save text content to a file example:
Public voidSave () {String data= "Data to save"; FileOutputStream out=NULL; BufferedWriter writer=NULL; Try{ out= Openfileoutput ("Data", context.mode_private); Writer=NewBufferedWriter (NewOutputStreamWriter (out)); Writer.write (data); } Catch(IOException e) {e.printstacktrace (); } finally{Try{if(Writer! =NULL) {writer.close (); }}Catch(IOException e) {e.printstacktrace (); }}}
We get a FileOutputStream object by Openfileoutput (), and then we use the FileOutputStream object to build a OutputStreamWriter object that lets you stream bytes into a character flow. Then use the OutputStreamWriter object build BufferedWriter Get BufferedWriter object, this corresponding stream uses buffer, can improve output efficiency, call BufferedWriter Write method writes data.
(2) Read the file
PublicString Load () {FileInputStream in=NULL; BufferedReader Reader=NULL; StringBuilder content=NewStringBuilder (); Try{ in= Openfileinput ("Data"); Reader=NewBufferedReader (NewInputStreamReader (in)); String Line= ""; while(line = Reader.readline ())! =NULL) {content.append (line); }}Catch(IOException e) {e.printstacktrace (); } finally{if(Reader! =NULL) {Try{reader.close (); } Catch(IOException e) {e.printstacktrace (); }}}returncontent.tostring ();}
The read context class for the file provides the Openfileinput () method, gets a FileInputStream object, and then constructs a InputStreamReader object using InputStreamReader. Turns bytes into a stream of characters. The BufferedReader object is then constructed. We then put the contents of the read into StringBuilder and finally called the ToString () method to return the data.
Not finished.
The persistence of Android learning