软件编程
位置:首页>> 软件编程>> Android编程>> Android基础教程数据存储之文件存储

Android基础教程数据存储之文件存储

作者:lqh  发布时间:2023-08-05 18:18:10 

标签:Android,数据存储

Android基础教程数据存储之文件存储

将数据存储到文件中并读取数据

1、新建FilePersistenceTest项目,并修改activity_main.xml中的代码,如下:(只加入了EditText,用于输入文本内容,不管输入什么按下back键就丢失,我们要做的是数据被回收之前,将它存储在文件中)


<?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()方法将一段文本内容保存到文件中,load()方法从文件中读取数据,套用)


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()保证在活动销毁之前一定调用这个方法
   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基础教程数据存储之文件存储

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!

来源:http://www.cnblogs.com/cxq1126/p/7220110.html

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com