1. 文件存储

比较适合存储简单的文本数据或二进制数据

1.1 将数据存储到文件

Context 类提供 openFileOutput 方法,用于将数据存储到指定文件,第一个参数是文件名,不包含路径,默认存储到 /data/data/packagename>/files/ 目录下。第二个参数是操作模式。

  • MODE_PRIVATE:默认模式,仅此应用可操作
  • MODE_APPEND:向文件追加
  • MODE_WORLD_READABLE:别的应用可读(被废弃)
  • MODE_WORLD_WRITEABLE:别的应用可读可写(被废弃)
public 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();
        }
    }
}

1.2 从文件中读取数据

context 的 openFileInput 方法

public String load() {
    FileInputStream in = null;
    BufferedReader reader = null;
    StringBuilder content = new StringBuilder();
    try {
        in = openFileInput("data");
        reader = new BufferedReader(new InputStreamReader(in));
        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();
}