Store data in a file and read data
1, new Filepersistencetest project, and modify Activity_ The code in Main.xml is as follows: (only added EditText, for entering text content, no matter what the input press the back key is lost, we have to do is the data is recycled before it is stored in the file)
1 <?xml version= "1.0" encoding= "Utf-8"?> 2 <linearlayout xmlns:android= "http://schemas.android.com/apk/res/android " 3 android:id=" @+id/activity_main " 4 Android Oid:layout_width= "Match_parent" 5 android:layout_height= "Match_parent" >< Span style= "COLOR: #008080" > 6 7 < EditText 8 android:id= "@+id/edit" 9 Android:layout_width= "Match_parent" 10 android:layout_height= "Wrap_co Ntent "11 android:hint=" Type something Here "/> </linearlayout>
2, modify the code in the Mainactivity, as follows: (Save () method saves a piece of text content to a file, the load () method reads data from the file, applies)
1 Public classMainactivityextendsappcompatactivity {2 PrivateEditText Edit;3 4 @Override5 protected voidonCreate (Bundle savedinstancestate) {6 Super. OnCreate (savedinstancestate);7 Setcontentview (r.layout.activity_main);8edit=(EditText) Findviewbyid (r.id.edit);9String inputtext=load ();Ten if(!Textutils.isempty (Inputtext)) {//non-null judgment of String One Edit.settext (inputtext); A edit.setselection (Inputtext.length ()); -Toast.maketext ( This, "Restoring succeeded", Toast.length_short). Show (); - } the - } - @Override - protected voidOnDestroy () {//rewrite OnDestroy () guarantees that this method must be called before the activity is destroyed + Super. OnDestroy (); -String inputtext=Edit.gettext (). toString (); + Save (Inputtext); A } at - Public voidSave (String inputtext) { -FileOutputStream out=NULL; -BufferedWriter writer=NULL; - Try{ -Out=openfileoutput ("Data", context.mode_private); inWriter=NewBufferedWriter (NewOutputStreamWriter (out)); - Writer.write (inputtext); to}Catch(IOException e) { + e.printstacktrace (); -}finally{ the Try{ * if(writer!=NULL){ $ writer.close ();Panax Notoginseng } -}Catch(IOException e) { the e.printstacktrace (); + } A } the } + - PublicString Load () { $FileInputStream in=NULL; $BufferedReader reader=NULL; -StringBuilder content=NewStringBuilder (); - Try{ theIn=openfileinput ("Data"); -Reader=NewBufferedReader (NewInputStreamReader (in));WuyiString line= ""; the while((Line=reader.readline ())! =NULL){ - Content.append (line); Wu } -}Catch(IOException e) { About e.printstacktrace (); $}finally { - if(reader!=NULL){ - Try{ - reader.close (); A}Catch(IOException e) { + e.printstacktrace (); the } - } $ } the returncontent.tostring (); the } the}
To run the program, the effect is as follows: (Press the back key after entering the content to return, reopen)
Android Learning-file storage for data storage