Android Learning 10 (Android file storage)

Source: Internet
Author: User

There are three main ways to implement data persistence in Android system, i.e. file storage, sharepreference storage and database storage. Of course, you can also save the data to the SD card.

File storage is the most basic kind of data storage in Android, it does not do any format word processing of the stored content, all the data is stored intact in the file, so it is more suitable for storing some simple text data or binary data.

A Openfileoutput () method is provided in the context class that can be used to store data in the specified file. This method receives two parameters, the first parameter is the name of the file, the name is used when creating the file, note that the file name specified here does not include the path, because all the files are stored by default in the/data/data/<package>/files/directory. The second parameter is the mode of operation of the file, the main 2 modes are optional, mode_private and mode_append. Where mode_private is the default mode of operation, which means that when the same file name is specified, the content that is written overwrites the contents of the original file, and Mode_append means that if the file already exists, it will append to the file and create a new file if it does not exist.

the Openfileoutput () method returns a FileOutputStream object that can be used to write data to a file using the Java stream.



Save the data to a file


Create an Android project with the project name Filepersistencetest and modify the code in the Activity_main.xml as follows:

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android"    xmlns:tools= "http// Schemas.android.com/tools "    android:layout_width=" match_parent "    android:layout_height=" Match_parent "     >   <edittext        android:id= "@+id/edit"       android:layout_width= "Match_parent"       android: layout_height= "Wrap_content"       android:hint= "type something here"       /></linearlayout>


The next thing we do is to save the data and save the data to the file when the activity is destroyed. To modify the code in Mainactivity:

Package Com.jack.filepersistencetest;import Java.io.bufferedwriter;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.outputstreamwriter;import Android.os.bundle;import android.app.Activity; Import Android.content.context;import Android.view.menu;import Android.widget.edittext;public class MainActivity Extends Activity {private EditText EditText; @Overrideprotected void OnCreate (Bundle savedinstancestate) { Super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); editText = (EditText) Findviewbyid ( R.id.edit);} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; This adds items to the action bar if it is PR Esent.getmenuinflater (). Inflate (R.menu.main, menu); return true;} public void Save (String inputtext) {fileoutputstream fileoutputstream=null;//file output stream object BufferedWriter bufferedwriter= null;//character Buffer Stream object try {//Initialize file output stream object Fileoutputstream=openfileoutput ("DataFile", context.mode_private);// Initialize character buffer Stream object Bufferedwriter=new Bufferedwriter (new OutputStreamWriter (FileOutputStream));//write String Bufferedwriter.write (Inputtext) to buffer memory;} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} Finally{try{if (bufferedwriter!=null) {bufferedwriter.close ();//Close File}}catch (Exception e) {e.printstacktrace ();}}} @Overrideprotected void OnDestroy () {//TODO auto-generated method Stubsuper.ondestroy (); String Inputtext=edittext.gettext (). toString ();//Gets the contents of the text box to save (inputtext);//Save the information in the text box}}


Call the Save method to save the contents of the text box when the OnDestroy method is called when the activity is destroyed. Run the program and enter Hello World in the text box, such as:



Then press the back key to close the program, and the content we entered is saved to the file. We can open Ddms's file Explorer to see. Entering the/data/data/com.jack.filepersistencetest/files/directory under the File Explorer, you can see that the datafile file is generated, such as:




Then click the left-most button on the right to export the file to your computer, and then open the file with a text editor, you can see the contents of the following:

You can verify that the contents of the text box are actually saved to the file.



Reading data from a file

Similar to storing data in a file the context class also provides a Openfileinput method for reading data from a file. This method is relatively simple, receive only one parameter, that is, the file name to read, then the system will automatically load the file into the/data/data/<package>/files/directory, and return a FileInputStream object, This object can then be read from the Java stream by the way it is obtained.

Modify the code in the Mainactivity, as follows:

Package Com.jack.filepersistencetest;import Java.io.bufferedreader;import Java.io.bufferedwriter;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.io.outputstreamwriter;import Android.os.Bundle; Import Android.app.activity;import android.content.context;import android.text.textutils;import android.view.Menu; Import Android.widget.edittext;import Android.widget.toast;public class Mainactivity extends Activity {private EditText EditText; @Overrideprotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_main); editText = (EditText) Findviewbyid (R.id.edit); String inputtext=load (); if (! Textutils.isempty (Inputtext)) {edittext.settext (inputtext); Edittext.setselection (Inputtext.length ()); Toast.maketext (This, "Restoring succeeded", Toast.length_short). Show ();}} @Overridepublic boolean Oncreateoptionsmenu (Menu menu) {//INflate the menu; This adds items to the action bar if it is present.getmenuinflater (). Inflate (R.menu.main, menu); return true;} public void Save (String inputtext) {fileoutputstream fileoutputstream=null;//file output stream object BufferedWriter bufferedwriter= null;//character Buffer Stream object try {//Initialize file output stream object Fileoutputstream=openfileoutput ("DataFile", context.mode_private);// Initializes the character buffer stream object Bufferedwriter=new bufferedwriter (new OutputStreamWriter (FileOutputStream));// Writes the string Bufferedwriter.write (Inputtext) to the buffered memory;} catch (Exception e) {//TODO auto-generated catch Blocke.printstacktrace ();} Finally{try{if (bufferedwriter!=null) {bufferedwriter.close ();//Close File}}catch (Exception e) {e.printstacktrace ();}}} @Overrideprotected void OnDestroy () {//TODO auto-generated method Stubsuper.ondestroy (); String Inputtext=edittext.gettext (). toString ();//Gets the contents of the text box inside save (Inputtext);//Saves the information in the text box}public String load () { FileInputStream in=null;//file input stream BufferedReader reader=null;//character buffer stream StringBuffer content=new StringBuffer ();// StringBuffer object try {in=openfileinput ("DAtafile ");//Get file input stream reader=new BufferedReader (new InputStreamReader (in));//Get Buffer object string line=" ";//while ((line= Reader.readline ())!=null) {//reads one line of content content.append (lines);//Add read contents to content}} catch (Exception e) {//TODO Auto-generated catch Blocke.printstacktrace ();} Finally{if (reader!=null) {try {reader.close ();//close Read stream} catch (IOException e) {//TODO auto-generated catch Blocke.printstacktrace ();}}} return content.tostring ();//Return string}}

The SetSelection method moves the input cursor to the end of the text to make it easier to enter, and then pops up a prompt to restore the success.

The Textutils.isempty () method can be used to judge 2 values at a time, and this method returns True when the passed string equals null or equal to an empty string, so that we do not need to judge these two null values alone.

Re-run the program with the following effects:




File storage is not suitable to save some more complex data, more complex data preservation methods, I will follow the line summary.



Reprint please specify to: http://blog.csdn.net/j903829182/article/details/40924441



Android Learning 10 (Android file storage)

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.