一、创建新项目,修改activity_main.xml中代码:在布局中加入 一个EditText,用于输入文本内容
<?xml version&#61;"1.0" encoding&#61;"utf-8"?>
<LinearLayout xmlns:android&#61;"http://schemas.android.com/apk/res/android"android:orientation&#61;"vertical"android:layout_width&#61;"match_parent"android:layout_height&#61;"match_parent"><EditTextandroid:id&#61;"&#64;&#43;id/edit"android:layout_width&#61;"match_parent"android:layout_height&#61;"wrap_content"android:hint&#61;"Type something here"/>
</LinearLayout>
二、在数据被回收之前&#xff0c;将它存储到文件当中&#xff0c;修改MainActivity&#xff1a;
①在onCreate方法中&#xff0c;获取EditText实例、②重写onDestroy方法&#xff0c;保证在活动销毁前调用它、
③调用save方法&#xff0c;把输入内容存储到文件中
public class MainActivity extends AppCompatActivity {private EditText edit;&#64;Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);edit&#61;(EditText) findViewById(R.id.edit);String inputText&#61;load();if (!TextUtils.isEmpty(inputText)){edit.setText(inputText);edit.setSelection(inputText.length());Toast.makeText(this,"Restoring succeeded",Toast.LENGTH_SHORT).show();}}&#64;Overrideprotected void onDestroy() {super.onDestroy();String inputText&#61;edit.getText().toString();save(inputText);}public void save(String inputText){FileOutputStream out&#61;null;BufferedWriter writer&#61;null;try {out&#61;openFileOutput("data", Context.MODE_PRIVATE);writer&#61;new BufferedWriter(new OutputStreamWriter(out));writer.write(inputText);} catch (IOException e) {e.printStackTrace();}finally {if (writer!&#61;null){try {writer.close();} catch (IOException e) {e.printStackTrace();}}}}
}
三、运行结果
输入内容&#xff0c;然后返回&#xff0c;此时输入内容被保存在文件中。验证&#xff1a;
总体思路&#xff1a;找到Android studio Monitor工具查看&#xff0c;新版AS找不到解决方法
在View->Tool Windows->Device File Explorer下面
找到后如下所示&#xff1a;打开/data/data/com.example.filepersistencetest/files/
找到生成的data文件
四、修改MainActivity代码使得重新启动时&#xff0c;EditText保留上次输入的内容&#xff1a;
现在将数据保存下来的功能实现了&#xff0c;接着实现下次程序启动的时候&#xff0c;数据还原到 EditText中&#xff0c;即如何从文件中读取数据
public String load(){FileInputStream in&#61;null;BufferedReader reader&#61;null;StringBuilder content&#61;new StringBuilder();try {in&#61;openFileInput("data");reader&#61;new BufferedReader(new InputStreamReader(in));String line&#61;"";while ((line&#61;reader.readLine())!&#61;null){content.append(line);}} catch (IOException e) {e.printStackTrace();}finally {if (reader!&#61;null){try {reader.close();} catch (IOException e) {e.printStackTrace();}}}return content.toString();}
五、运行结果
输入内容后重新启动程序查看
完成文件存储&#xff01;