File Storage for Android Data Persistence

File Storage for Android Data Persistence

The realization of this paper is to save the data to the file and read it out when needed. This method is only applicable to data of simple type.

Data stored in files

Once you understand the Java input and output streams, you can see. openFileOutput receives two parameters, the first is the name of the file (without path), the second is the mode of operation of the file, MODE_PRIVATE represents the new content will cover the old content, and MODE_APPEND represents the additional content after the original content.

/**
     * Save data to file
     * @param inputString
     */
    private void saveToFile(String inputString) {
        FileOutputStream fileOutputStream=null;
        BufferedWriter writer = null;
        try {
            fileOutputStream = openFileOutput("data",MODE_PRIVATE);
            writer = new BufferedWriter(new OutputStreamWriter(fileOutputStream));
            try {
                writer.write(inputString);
            } catch (IOException e) {
                e.printStackTrace();
            }finally {
                if (writer!=null){
                    try {
                        writer.close();
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
    }

Read stored data from a file

/**
     * Getting data from a file
     * @return
     */
    private String loadDataByFile() {
        FileInputStream inputStream = null;
        BufferedReader reader = null;
        StringBuilder content = new StringBuilder();
        try {
            inputStream = openFileInput("data");
            reader = new BufferedReader(new InputStreamReader(inputStream));
            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();

    }

The implementation of this article is very simple, and of course, it only applies to individual exercises. Generally, formal projects of companies have direct databases to store data, and direct file storage is not allowed.

Tags: Android Java

Posted on Sun, 06 Oct 2019 20:00:21 -0700 by zero-one