Android基礎教程數(shù)據(jù)存儲之文件存儲
更新時間:2017年07月22日 08:44:29 投稿:lqh
這篇文章主要介紹了Android基礎教程數(shù)據(jù)存儲之文件存儲的相關資料,數(shù)據(jù)存儲是Android開發(fā)的重要的知識,這里提供了實例,需要的朋友可以參考下
Android基礎教程數(shù)據(jù)存儲之文件存儲
將數(shù)據(jù)存儲到文件中并讀取數(shù)據(jù)
1、新建FilePersistenceTest項目,并修改activity_main.xml中的代碼,如下:(只加入了EditText,用于輸入文本內(nèi)容,不管輸入什么按下back鍵就丟失,我們要做的是數(shù)據(jù)被回收之前,將它存儲在文件中)
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Type something here"/>
</LinearLayout>
2、修改MainActivity中的代碼,如下:(save()方法將一段文本內(nèi)容保存到文件中,load()方法從文件中讀取數(shù)據(jù),套用)
public class MainActivity extends AppCompatActivity {
private EditText edit;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
edit=(EditText) findViewById(R.id.edit);
String inputText=load();
if(!TextUtils.isEmpty(inputText)){ //對字符串進行非空判斷
edit.setText(inputText);
edit.setSelection(inputText.length());
Toast.makeText(this,"Restoring succeeded",Toast.LENGTH_SHORT).show();
}
}
@Override
protected void onDestroy(){ //重寫onDestroy()保證在活動銷毀之前一定調(diào)用這個方法
super.onDestroy();
String inputText=edit.getText().toString();
save(inputText);
}
public void save(String inputText){
FileOutputStream out=null;
BufferedWriter writer=null;
try{
out=openFileOutput("data", Context.MODE_PRIVATE);
writer=new BufferedWriter(new OutputStreamWriter(out));
writer.write(inputText);
}catch(IOException e){
e.printStackTrace();
}finally{
try{
if(writer!=null){
writer.close();
}
}catch(IOException e){
e.printStackTrace();
}
}
}
public String load(){
FileInputStream in=null;
BufferedReader reader=null;
StringBuilder content=new StringBuilder();
try{
in=openFileInput("data");
reader=new BufferedReader(new InputStreamReader(in));
String line="";
while((line=reader.readLine())!=null){
content.append(line);
}
}catch(IOException e){
e.printStackTrace();
}finally {
if(reader!=null){
try{
reader.close();
}catch (IOException e){
e.printStackTrace();
}
}
}
return content.toString();
}
}
運行程序,效果如下:(輸入content后按back鍵返回,重新打開)

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!
您可能感興趣的文章:
- android?studio數(shù)據(jù)存儲建立SQLite數(shù)據(jù)庫實現(xiàn)增刪查改
- Android 通過SQLite數(shù)據(jù)庫實現(xiàn)數(shù)據(jù)存儲管理
- Android四種數(shù)據(jù)存儲的應用方式
- Android SharedPreferences實現(xiàn)數(shù)據(jù)存儲功能
- android使用SharedPreferences進行數(shù)據(jù)存儲
- Android開發(fā)教程之ContentProvider數(shù)據(jù)存儲
- 詳解Android的網(wǎng)絡數(shù)據(jù)存儲
- 5種Android數(shù)據(jù)存儲方式匯總
- 詳解Android數(shù)據(jù)存儲之SQLCipher數(shù)據(jù)庫加密
- Android 單例模式實現(xiàn)可復用數(shù)據(jù)存儲的詳細過程
Android webview加載https鏈接錯誤或無響應的解決
這篇文章主要介紹了Android webview加載https鏈接錯誤或無響應的解決,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
2020-03-03 
