将数据存储到文件中并读取数据
1、新建FilePersistenceTest项目,并修改activity_main.xml中的代码,如下:(只加入了EditText,用于输入文本内容,不管输入什么按下back键就丢失,我们要做的是数据被回收之前,将它存储在文件中)
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:layout_width="match_parent" 5 android:layout_height="match_parent"> 6 7 <EditText 8 android:id="@+id/edit" 9 android:layout_width="match_parent" 10 android:layout_height="wrap_content" 11 android:hint="Type something here"/> 12 </LinearLayout>
2、修改MainActivity中的代码,如下:(save()方法将一段文本内容保存到文件中,load()方法从文件中读取数据,套用)
1 public class MainActivity extends AppCompatActivity { 2 private EditText edit; 3 4 @Override 5 protected void onCreate(Bundle savedInstanceState) { 6 super.onCreate(savedInstanceState); 7 setContentView(R.layout.activity_main); 8 edit=(EditText) findViewById(R.id.edit); 9 String inputText=load(); 10 if(!TextUtils.isEmpty(inputText)){ //对字符串进行非空判断 11 edit.setText(inputText); 12 edit.setSelection(inputText.length()); 13 Toast.makeText(this,"Restoring succeeded",Toast.LENGTH_SHORT).show(); 14 } 15 16 } 17 @Override 18 protected void onDestroy(){ //重写onDestroy()保证在活动销毁之前一定调用这个方法 19 super.onDestroy(); 20 String inputText=edit.getText().toString(); 21 save(inputText); 22 } 23 24 public void save(String inputText){ 25 FileOutputStream out=null; 26 BufferedWriter writer=null; 27 try{ 28 out=openFileOutput("data", Context.MODE_PRIVATE); 29 writer=new BufferedWriter(new OutputStreamWriter(out)); 30 writer.write(inputText); 31 }catch(IOException e){ 32 e.printStackTrace(); 33 }finally{ 34 try{ 35 if(writer!=null){ 36 writer.close(); 37 } 38 }catch(IOException e){ 39 e.printStackTrace(); 40 } 41 } 42 } 43 44 public String load(){ 45 FileInputStream in=null; 46 BufferedReader reader=null; 47 StringBuilder content=new StringBuilder(); 48 try{ 49 in=openFileInput("data"); 50 reader=new BufferedReader(new InputStreamReader(in)); 51 String line=""; 52 while((line=reader.readLine())!=null){ 53 content.append(line); 54 } 55 }catch(IOException e){ 56 e.printStackTrace(); 57 }finally { 58 if(reader!=null){ 59 try{ 60 reader.close(); 61 }catch (IOException e){ 62 e.printStackTrace(); 63 } 64 } 65 } 66 return content.toString(); 67 } 68 }
运行程序,效果如下:(输入content后按back键返回,重新打开)