Android learning-data storage-file storage, android file storage
Store data in files and read data
1. Create a FilePersistenceTest project and modify the code in activity_main.xml as follows: (only EditText is added for text input. No matter what you enter, press the back key to lose the content, what we need to do is store the data in the file before it is recycled)
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. modify the code in MainActivity as follows: (the save () method saves a piece of text content to the file, and the load () method reads data from the file and applies it)
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)) {// Non-empty judgment on string
11 edit.setText (inputText);
12 edit.setSelection (inputText.length ());
13 Toast.makeText (this, "Restoring succeeded", Toast.LENGTH_SHORT) .show ();
14}
15
16}
17 @Override
18 protected void onDestroy () {// Override onDestroy () to ensure that this method must be called before the activity is destroyed
19 super.onDestroy ();
20 String inputText = edit.getText (). ToString ();
21 save (inputText);
twenty two }
twenty three
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}
Run the program. The result is as follows: (enter content and press back to return and re-open it)