Self-study Android notes-file storage

Source: Internet
Author: User

1. Introduction to file Storage:

File storage is a basic form of data storage for Android, similar to the file store in Java, which is stored as an I/O stream intact in the document, in contrast, the file storage in Android is divided into internal storage and external storage.


2. Internal storage:

Internal storage means that the data in an application is stored in a file in the internal storage space of the device. By default, files that are stored in internal storage are private to the application, and you need to set permissions if other applications want to manipulate the files in the application. When the user uninstalls the application, the data stored internally is purged.

Internal Storage uses the Openfileoutput () method and the Openfileinput () method provided by the context to obtain Fileoutputotream objects and FileInputStream objects, respectively, by these two methods. Specific as follows:

FileOutputStream openfileoutput (String name, int mode); FileInputStream openfileinput (String name);

Where the parameter name represents the file name, mode indicates how the files are operated, that is, the way the file is read and written, it has 4 values, as follows:

Mode_private: Default mode of operation, the file can only be read and written by the current program
Mode_append: The mode checks whether the file exists, appends content to the file, or creates a new file.
Mode_world_readable: Indicates that the current file can be read by another application
Mode_world_writeable: Indicates that the current file can be written by another application


The sample code that uses the FileOutputStream object to store data in a file when storing data is as follows:

        String filename= "Data.txt";        String content= "HelloWorld";        FileOutputStream Fos;        try {            fos = openfileoutput (filename, mode_private);            Fos.write (Content.getbytes ());            Fos.close ();        } catch (Exception e) {            e.printstacktrace ();        }    

The sample code for reading data using the FileInputStream object is as follows when extracting data:

        String content= "";        FileInputStream fis;        try{                        fis=openfileinput ("Data.txt");            Byte[] Buffer=new byte[fis.available ()];            Fis.read (buffer);            Content=new String (buffer);        } catch (Exception e) {            e.printstacktrace ();        }

3. External storage:

External storage refers to the storage of files on some peripheral devices, such as an SD card or a memory card embedded in the device, which is a permanent means of storage. Files saved to the external storage are public and can be modified by the user.

When you use an external storage device, you should always first call the Environment.getexternalstoragestate () method to check the availability of the external storage device.


Sample code to store data in a peripheral device (SD card) is as follows:

           String state= environment.getexternalstoragestate ();            if (State.equals (environment.media_mounted)) {                File sdpath=environment.getexternalstoragedirectory ();                File File=new file (Sdpath, "data.txt");                String data= "HelloWorld";                FileOutputStream Fos;                try {                    fos=new fileoutputstream (file);                    Fos.write (Data.getbytes ());                    Fos.close ();                } catch (Exception e) {                    e.printstacktrace ();                }            }

The sample code for reading data from a peripheral device (SD card) is as follows:

            String state= environment.getexternalstoragestate ();            if (State.equals (environment.media_mounted)) {                File sdpath=environment.getexternalstoragedirectory ();                File File=new file (Sdpath, "data.txt");                FileInputStream fis;                try {                    fis=new fileinputstream (file);                    BufferedReader br=new BufferedReader (New InputStreamReader (FIS));                    String data=br.readline ();                } catch (Exception e) {                    e.printstacktrace ();                }            }

4. Case--Storing user information1. Create the program:

Activity_main:


<relativelayout 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 "Tools:context =". Mainactivity "> <textview android:id=" @+id/textview1 "android:layout_width=" Wrap_content "and         roid:layout_height= "Wrap_content" android:layout_alignparenttop= "true" android:layout_alignparentleft= "true"        Android:textsize= "20DP" android:text= "Please enter the information you want to store:"/> <edittext android:id= "@+id/et_info" Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" Android:layout_alignparentleft = "true" android:layout_below= "@+id/textview1" android:ems= "/> <button android:id=" @+id/bt N_read "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "android:layout_align right= "@+id/et_info" android:layout_below= "@+id/et_info" android:text= "read information"/> <button android:id= "@+id/btn_save" android:layou T_width= "Wrap_content" android:layout_height= "Wrap_content" android:layout_alignparentleft= "true" and roid:layout_below= "@+id/et_info" android:text= "Save Information"/></relativelayout>


2. Write the Interface Interaction code:

Mainactivity:

Package Select.itcast.cn.cunchuxinxi;import Android.app.activity;import Android.content.context;import Android.os.bundle;import Android.os.environment;import Android.view.menu;import Android.view.MenuItem;import Android.view.view;import Android.widget.button;import Android.widget.edittext;import Android.widget.Toast;import Java.io.bufferedreader;import Java.io.fileinputstream;import Java.io.filenotfoundexception;import Java.io.fileoutputstream;import Java.io.ioexception;import Java.io.inputstreamreader;import Java.nio.Buffer;    public class Mainactivity extends Activity {private EditText et_info;    Private Button Btn_save;    Private Button Btn_read;        @Override protected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate);        Setcontentview (R.layout.activity_main);        Gets the control et_info= (EditText) Findviewbyid (r.id.et_info) in the layout file;        Btn_save= (Button) Findviewbyid (R.id.btn_save); Btn_read= (Button) Findviewbyid (R.id.btn_read);        Btn_save.setonclicklistener (New Buttonlistener ());    Btn_read.setonclicklistener (New Buttonlistener ()); } Private class Buttonlistener implements view.onclicklistener{public void OnClick (View v) {switch (                    V.getid ()) {case r.id.btn_save:string saveinfo=et_info.gettext (). toString (). Trim ();                    FileOutputStream Fos;                        try{//Save Data Fos=openfileoutput ("Data.txt", context.mode_append);                        Fos.write (Saveinfo.getbytes ());                    Fos.close ();                    } catch (FileNotFoundException e) {e.printstacktrace ();                    } catch (IOException e) {e.printstacktrace ();                    } toast.maketext (Mainactivity.this, "Save data Succeeded", 0). Show ();                Break Case R.id.btn_read:string ContenT= "";                        try{//Get Saved Data FileInputStream fis=openfileinput ("Data.txt");                        Byte[] Buffer=new byte[fis.available ()];                        Fis.read (buffer);                    Content=new String (buffer);                    } catch (FileNotFoundException e) {e.printstacktrace ();                    } catch (IOException e) {e.printstacktrace ();                    } toast.maketext (Mainactivity.this, "Saved data is:" +content,0). Show ();                Break            Default:break; }}} @Override public boolean Oncreateoptionsmenu (Menu menu) {//Inflate the menu; this adds item        s to the action Bar if it is present.        Getmenuinflater (). Inflate (R.menu.menu_main, menu);    return true; } @Override public boolean onoptionsitemselected (MenuItem Item) {//Handle actIon bar item clicks here.  The action bar would//automatically handle clicks on the Home/up button, so long/As you specify a parent        Activity in Androidmanifest.xml.        int id = item.getitemid ();        Noinspection simplifiableifstatement if (id = = r.id.action_settings) {return true;    } return super.onoptionsitemselected (item); }}

3. Run the program:


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Self-study Android notes-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.