標籤:layout tac oncreate read height red 讀取 err null
將資料存放區到檔案中並讀取資料
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 @Override18 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鍵返回,重新開啟)
Android學習——資料存放區之檔案儲存體