Android Read-Write file example

Source: Internet
Author: User

(1) Procedure description

The two buttons in the code handle the events, respectively, and read and write the text.

1) File write operation

First call the activity's Openfileoutput () method to get the output stream of the text file, the first parameter is the name of the text file, and the second is how the file is opened

The write () method of the OutputStream object is then called to write the text information in TextView to the OutputStream object, and the close () method is finally called to complete the write operation.

2) file read operation

First call the activity's Openfileinput () method to get the input stream of the text file,

The read () method of the input stream object is then called to read the byte information in the input stream into a Bytearrayoutputstream object, and finally convert the Bytearrayoutputstream to a string displayed in TextView

(2) Layout file

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "Android:layout_width=" Fill_parent "android:layout_height=" fill_parent "android:orientation=" vertical "&G    T <relativelayout android:layout_width= "fill_parent" android:layout_height= "Wrap_content" Android:or ientation= "vertical" > <textview android:id= "@+id/label_01" android:layout_width= "Wrap_ Content "android:layout_height=" wrap_content "android:text=" @string/name "Android:textsiz            E= "20DP"/> <edittext android:id= "@+id/filename" android:layout_width= "160DP" android:layout_height= "Wrap_content" android:layout_aligntop= "@id/label_01" android:layout_toright of= "@id/label_01"/> </RelativeLayout> <textview android:id= "@+id/label_02" android:layout        _width= "Wrap_content"android:layout_height= "Wrap_content" android:text= "@string/neirong"/> <edittext android:id= "@+id/c        Ontent "android:layout_width=" fill_parent "android:layout_height=" 120px "android:ems=" > <requestfocus/> </EditText> <linearlayout android:layout_width= "Fill_parent" Android: layout_height= "wrap_content" android:orientation= "horizontal" > <button android:id= "@+id/sa Vebutton "android:layout_width=" wrap_content "android:layout_height=" Wrap_content "Androi            D:gravity= "Right" android:text= "@string/save"/> <button android:id= "@+id/readbutton" Android:layout_width= "Wrap_content" android:layout_height= "Wrap_content" android:gravity= " Right "android:text=" @string/read "/> </LinearLayout> <textview android:id=" @+id/textc Ontent "Android:lAyout_width= "Match_parent" android:layout_height= "Wrap_content" android:layout_weight= "0.10"/></Linea Rlayout>

(2) Code

Package Com.liuzuyi.file;import Java.io.bytearrayoutputstream;import Java.io.inputstream;import Java.io.outputstream;import Android.support.v7.app.actionbaractivity;import Android.support.v7.app.ActionBar; Import Android.support.v4.app.fragment;import Android.app.activity;import Android.content.context;import Android.os.bundle;import Android.util.log;import Android.view.layoutinflater;import Android.view.Menu;import Android.view.menuitem;import Android.view.view;import Android.view.view.onclicklistener;import Android.view.viewgroup;import Android.widget.button;import Android.widget.edittext;import Android.widget.TextView Import Android.widget.toast;import Android.os.build;public class Mainactivity extends Activity {private EditText Filename;private EditText context;private TextView textcontent;private static final String tag= "Simplefile";p rotected void OnCreate (Bundle savedinstancestate) {super.oncreate (savedinstancestate); Setcontentview (r.layout.activity_ Main); Filename= (EditText) findViewbyid (R.id.filename); context= (EditText) Findviewbyid (r.id.content); textcontent= (TextView) Findviewbyid ( R.id.textcontent); Button savebtn= (button) This.findviewbyid (R.id.savebutton); Button viewbtn= (button) This.findviewbyid (R.id.readbutton); Savebtn.setonclicklistener (L);   Viewbtn.setonclicklistener (l);}  Private View.onclicklistener L =new Onclicklistener () {public void OnClick (View v) {button button = (button) v;  String namestr = Filename.gettext (). toString (). Trim ();  String contentstr =context.gettext (). toString (); Switch (Button.getid ()) {case R.id.savebutton:string resid_s = "Success"; OutputStream filsos= null;try {filsos= MainActivity.this.openFileOutput (namestr+ ". txt", context.mode_append); Filsos.write (Contentstr.getbytes ()); Filsos.close ();} catch (Exception e) {resid_s = "faile"; E.printstacktrace ();} Toast.maketext (Mainactivity.this, Resid_s,toast.length_long). Show (); LOG.I (TAG, NAMESTR); LOG.I (TAG, contentstr); break;case r.id.readbutton:string resid_v = "Success"; InputStream Filsis= null; String contentst = null;try {filsis=mainactivity.this.openfileinput (namestr+ ". txt");  Bytearrayoutputstream OStream = new Bytearrayoutputstream (); byte[] buffer = new Byte[1024];int len =-1;  while (len = filsis.read (buffer))! =-1) {ostream.write (Buffer,0,len);}  Contentst=ostream.tostring ();  Ostream.close (); Filsis.close ();} catch (Exception e) {resid_v = "faile"; E.printstacktrace ();} Textcontent.settext (CONTENTST); LOG.I (TAG, CONTENTST); Toast.maketext (Mainactivity.this, Resid_v,toast.length_long). Show ();  LOG.I (TAG,NAMESTR); break;} }    };}



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.