Android: file storage of learning notes of data storage scheme (openFileOutput, openFileInput)

file store

1, Functions to be implemented

Save the data in the input box to the file with the specified file name to realize data persistence; If the data has been saved, the data saved in the file will be read out and displayed in the input box when the activity starts next time.

2, Basic knowledge

  • 1. Use a callback function onDestroy() in the activity life cycle to write data to a file before the activity is destroyed. For example, when the return key is pressed, the activity is destroyed and the code in this method will be executed.
  • 2. Using the isEmpty(CharSequence str) method in TextUtils, you can easily judge whether a string variable is null and whether the string is an empty string (string length is 0). The traditional way in java is as follows:
    If (string! = null & & string. Length()! = 0), this method is troublesome, and TextUtils is more convenient.

3. ① a FileOutputStream object can be obtained by using the openFileOutput (String name, int mode) method in the context class. The first parameter of this method is the file name, and the second parameter is the operation mode of the file. The main values are MODE_PRIVATE, MODE_APPEND: if the file already exists, the first method will overwrite the original content in the file, and the second method is to add data on the original basis.

② openFileInput(String name) in the Contex class can be used to obtain a FileInputStream object. The parameter passed in the method is the name of the file.

In addition, there is nothing special about file reading and writing operations. All of them use IO knowledge in JDK. Here, buffered character stream is also used to improve the speed of reading and writing.

3, Use

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 et;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        et=findViewById(R.id.et);
        String load = load();
        if (!TextUtils.isEmpty(load))//If the file exists
        {
            et.setText(load);
            et.setSelection(load.length());//Move the cursor to the end of the input box
            Toast.makeText(this,"Data recovery from file succeeded!",Toast.LENGTH_SHORT).show();
        }
    }

    @Override
    protected void onDestroy()//Save the data to a file before the activity is destroyed
    {
        super.onDestroy();
        String string = et.getText().toString();
        save(string);
    }

    /**
     * Writing text data to a file
     * @param inputText
     */
    private void save(String inputText)
    {
        FileOutputStream fileOutputStream=null;
        BufferedWriter bufferedWriter=null;
        try
        {
            fileOutputStream=openFileOutput("info.txt",MODE_PRIVATE);
            bufferedWriter=new BufferedWriter(new OutputStreamWriter(fileOutputStream));
            bufferedWriter.write(inputText);
        } catch (Exception e)
        {
            System.out.println(e);
        }
        finally
        {
            if (bufferedWriter!=null)
            {
                try
                {
                    bufferedWriter.close();
                } catch (IOException e)
                {
                    System.out.println(e);
                }
            }

        }
    }


    /**
     * Read data from file
     * @return
     */
    private String load()
    {
        FileInputStream fileInputStream=null;
        BufferedReader bufferedReader=null;
        StringBuilder stringBuilder=new StringBuilder();
        try
        {
            fileInputStream= openFileInput("info.txt");
            bufferedReader=new BufferedReader(new InputStreamReader(fileInputStream));
            String line="";
            while ((line=bufferedReader.readLine())!=null)
            {
                stringBuilder.append(line);
            }
        } catch (Exception e)
        {
            System.out.println(e);
        }
        finally
        {
            if (bufferedReader!=null)
            {
                try
                {
                    bufferedReader.close();
                } catch (IOException e)
                {
                    System.out.println(e);
                }
            }
        }
        return stringBuilder.toString();
    }
}


Points to note:

  • The first parameter of the function Context.openFileOutput means the file name. You cannot add a path because the file is stored in the / data / package name / flies directory by default
  • There are several methods to note in onCreate: TextUtil.isEmpty(string) this method will judge the null and null string as true, thus avoiding the trouble of considering the two problems separately. Then, the setSelection function is used to set the cursor position of EditText.

Layout code:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

   <EditText
       android:id="@+id/et"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:gravity="center"
       android:hint="Please enter the information you want to save"/>

The following are two screenshots of the effect in the simulator.

Enter the text message to save:

After saving the file, open the program next time:

reference resources

Keywords: Java Android

Added by misterguru on Wed, 10 Nov 2021 05:55:15 +0200