Skip to content

Instantly share code, notes, and snippets.

@dearsq
Created July 31, 2018 08:08
Show Gist options
  • Save dearsq/867151c42b466963b906ff63f89ce5c8 to your computer and use it in GitHub Desktop.
Save dearsq/867151c42b466963b906ff63f89ce5c8 to your computer and use it in GitHub Desktop.
[数据持久化_文件存储] 文件存储 #Android

    /**
     * 文件名 为 data
     * @param inputText
     */
    private 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;
        StringBuilder content = new StringBuilder();

        try {
            // openFileInput 获取 FileInputStream 对象
            in = openFileInput("data");
            // 构建 BufferedReader 对象
            reader = new BufferedReader(new InputStreamReader(in));
            String line = "";
            // 一行行的读, 读到的内容存在 StringBuilder 中
            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();
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment