数据持久化:将内存中的瞬时数据保存到存储设备中
主要有三种方式:
1. 文件存储
2. SharedPreference存储
3. 数据库存储
4. 还可以存到SD,相对于以上三种,安全性较差
一 文件存储与读取
main_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
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>
package com.example.filepersistencetest;
import android.content.Context;
import android.support.v4.text.TextUtilsCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.TextUtils;
import android.widget.EditText;
import android.widget.Toast;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
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)){ //TextUtils.isEmpty()一次性对两种空值进行判断,当传入的字符串等于空或等于空字符串时返回值都为true
edit.setText(inputText);
edit.setSelection(inputText.length());//把光标移动到末尾,以便再次输入
Toast.makeText(this ,"Restoring succeeded" ,Toast.LENGTH_SHORT ).show();
}
}
@Override
protected void 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;
StringBuffer content =new StringBuffer();
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();
}
}
总结:1.TextUtils.isEmpty()的使用
2.MODE_PRIVATE 模式为覆盖原文件的内容
MODE_APPEND 为在原文件中追加内容
3.java文件的写入和读出操作