文件存储

将数据存储到文件中
private void save() {
    String data = "这是获取的数据";
    try {
        FileOutputStream out = openFileOutput("data", Context.MODE_APPEND);
        writer = new BufferedWriter(new OutputStreamWriter(out));
        writer.write(data);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        try {
            if (writer != null)
                writer.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
  1. 通过openFileOutput()方法能够得到一个FileOutputStream对象
  2. 再借助它构建一个OutputStreamWriter对象
  3. 再使用OutputStreamWriter构建出一个BufferedWriter对象
  4. 最后通过BufferedWriter将数据写入到文件中
 
从文件中读取数据
private String load() {
    StringBuilder content = new StringBuilder();
    BufferedReader reader = null;
    try {
        FileInputStream in = openFileInput("data");
        reader = new BufferedReader(new InputStreamReader(in));
        String line = "";
        while ((line = reader.readLine())!= null)
            content.append(line);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        if (reader != null){
            try {
                reader.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return content.toString();
}
  1. 通过openFileInput()方法能够得到一个FileInputStream对象
  2. 再借助它构建一个InputStreamReader对象
  3. 再使用InputStreamReader 构建出一个BufferedReader对象
  4. 通过BufferedReader进行一行行读取,并存放在StringBuilder中,最后将读取到的内容返回即可
posted @ 2018-01-26 21:33  品味Code  阅读(160)  评论(0编辑  收藏  举报