Android data storage and IO (ii)

Source: Internet
Author: User

2.SD card Read and write operation


1 Read and write SD card first to add read and Write permissions

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M01/5B/91/wKioL1UM-cvTlto1AAD9cHO8_Pc915.jpg "title=" Qq20150321110532.png "alt=" wkiol1um-cvtlto1aad9cho8_pc915.jpg "/>2. Build a layout file to receive and display data

<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"  android:paddingleft= "@dimen/activity_horizontal_margin"      android:paddingright= "@dimen/activity_horizontal_margin"     android: paddingtop= "@dimen/activity_vertical_margin"     android:paddingbottom= "@dimen/activity_ Vertical_margin " tools:context=". Mainactivity ">    <button        android:id= "@+id/buttonwrite"         android:layout_width= "Wrap_content"          android:layout_height= "Wrap_content"          android:text= "Write Data"         android:layout_aligNparenttop= "true"         android:layout_centerhorizontal= "true"  / >    <edittext        android:id= "@+id/edit"         android:layout_width= "Fill_parent"          android:layout_height= "Wrap_content"          android:layout_below= "@+id/buttonwrite"         android:layout_ Alignparentleft= "true"         android:layout_alignparentstart= "true"  />    <button        android:id= "@+id/ Buttonreade "        android:layout_width=" Wrap_content "         android:layout_height= "Wrap_content"          android:text= "reading Data"        android:layout_below= "@+id/edit"          android:layout_alignleft= "@+id/buttonwrite"          Android:layout_alignstart= "@+id/buttonwrite"         android:layout_ margintop= "73DP"  />    <TextView         android:id= "@+id/textview"         android:layout_width= "Wrap_ Content "        android:layout_height=" Wrap_content "         android:text= "Yu"         android: Textsize= "20SP"         android:layout_alignparentbottom= "true"          android:layout_centerhorizontal= "true"          android:layouT_marginbottom= "167DP"  /></RelativeLayout> 

3.

package xiaocool.net.sdtest;import android.os.bundle;import android.os.environment;import  android.support.v7.app.actionbaractivity;import android.view.menu;import android.view.menuitem; Import android.view.view;import android.widget.button;import android.widget.edittext;import  android.widget.TextView;import java.io.BufferedReader;import java.io.File;import  Java.io.fileinputstream;import java.io.inputstreamreader;import java.io.randomaccessfile;public  class MainActivity extends ActionBarActivity {    private  Final  string file_name= "/xiaocool.bin";     private button write, Read;    private edittext edittext;    private textview  textView;     @Override     protected void oncreate ( Bundle savedinstancestate)  {        super.oncreate (savedinstancestate);         setcontentview (R.layout.activity_main);         write= (Button) This.findviewbyid (r.id.buttonwrite);         read= ( Button) This.findviewbyid (R.id.buttonreade);         edittext= (EditText) This.findviewbyid (R.id.edit);         textview= (TextView) This.findviewbyid (R.id.textview);         write.setonclicklistener (new  view.onclicklistener ()  {            @ Override            public void onclick ( VIEW&NBSP;V)  {                 write (Edittext.gettext (). toStRing ());                 Edittext.settext ("");            }         });         read.setonclicklistener (New view.onclicklistener ()  {              @Override             public void  OnClick (VIEW&NBSP;V)  {                 textview.settext (Read ());             }        });     }    // Method of writing data to SD card     private void write (string content) {     try{        //if the phone is plugged into an SD card, and   has access to the SD card         if ( Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {             //get the SD card directory              file sdcraddir=environment.getexternalstoragedirectory ();             file targetfile=new file (Sdcraddir.getcanonicalpath () +FILE_NAME) ;             //create randomaccessfile   with the specified file           RandomAccessFile raf=new  Randomaccessfile (TargetFile, "RW");             // Move the file record pointer to the last             raf.seek (TargetFile.length ( ));             //Output File Contents              raf.write (Content.getbytes ());             // Close             raf.close ();         }    }catch  (exception e) {         e.printstacktrace ();        }     }    //reading data from SD card     private string read () {        try {           if ( Environment.getexternalstoragestate (). Equals (environment.media_mounted)) {                file sdcarddir= Environment.getexternalstoragedirectory ();                //get the input stream corresponding to the development file                 FileInputStream file=new  FileInputStream (Sdcarddir.getcanonicalpath () +file_name);                //the developed input stream into a bufferreader                bufferedreader br=new bufferedreader (new  InputStreamReader (file));                stringbuilder sb=new stringbuilder ("");                String line=null;                //Loop Read File contents                 whilE ((Line=br.readline ())!=null) {                    sb.append (line);                }                //Close                 br.close ();                Return sb.tostring ();           }        }catch  (exception e) {            e.printstacktrace ();       }         return null;    }     @Override      public boolean&nbSp;oncreateoptionsmenu (Menu menu)  {        // inflate  the menu; this adds items 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 will         // 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);     }}


This article is from the "Ahu-on-the-road" blog, be sure to keep this source http://xiaocool.blog.51cto.com/1593956/1622746

Android data storage and IO (ii)

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.