IO Programming: Memory card and SD card. The string is stored in the memory card and read out.
Activity
Packagecom.sxt.day06_06;ImportJava.io.FileInputStream;Importjava.io.FileNotFoundException;ImportJava.io.FileOutputStream;Importjava.io.IOException;Importjava.io.UnsupportedEncodingException;Importandroid.app.Activity;ImportAndroid.os.Bundle;ImportAndroid.view.View;ImportAndroid.view.View.OnClickListener;ImportAndroid.widget.EditText;ImportAndroid.widget.Toast; Public classMainactivityextendsActivity {EditText met;//text Box@Overrideprotected voidonCreate (Bundle savedinstancestate) {Super. OnCreate (savedinstancestate); Setcontentview (R.layout.activity_main); Initview (); Setlistener (); } Private voidSetlistener () {Setsavedataclicklistener (); Setreaddataclicklistener (); } Private voidSetreaddataclicklistener () {Findviewbyid (r.id.btnreaddata). Setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {FileInputStream in=NULL; Try{ in= Openfileinput ("file.dat"); byte[] Data=New byte[1024]; intLen = in.read (data);//returns the number of bytes actually readString text=NewString (data, 0, Len, "Utf-8")); Toast.maketext (mainactivity. This, text, 3000). Show (); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }finally{ if(in!=NULL){ Try{in.close (); } Catch(IOException e) {e.printstacktrace (); } } } } }); } Private voidSetsavedataclicklistener () {Findviewbyid (r.id.btnsavedata). Setonclicklistener (NewOnclicklistener () {@Override Public voidOnClick (View v) {FileOutputStream out=NULL; Try{ out=openfileoutput ("file.dat", mode_private); String text=Met.gettext (). toString (); byte[] Data=text.getbytes ("Utf-8");//FileOutputStream when data is converted to a byte arrayout.write (data); Out.flush (); } Catch(FileNotFoundException e) {e.printstacktrace (); } Catch(unsupportedencodingexception e) {e.printstacktrace (); } Catch(IOException e) {e.printstacktrace (); }finally{ if(out!=NULL){ Try{out.close (); } Catch(IOException e) {e.printstacktrace (); } } } } }); } Private voidInitview () {met=(EditText) Findviewbyid (r.id.et); }}
Page
<LinearLayoutxmlns:android= "Http://schemas.android.com/apk/res/android"Android:layout_width= "Match_parent"Android:layout_height= "Match_parent"android:orientation= "vertical"> <EditTextAndroid:id= "@+id/et"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Hello, Zhang Fei!" "/> <ButtonAndroid:id= "@+id/btnsavedata"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Save Data" /> <ButtonAndroid:id= "@+id/btnreaddata"Android:layout_width= "Match_parent"Android:layout_height= "Wrap_content"Android:text= "Read Data" /> </LinearLayout>
Android + IO programming