文件存储
将数据存储到文件中
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(); } } }
- 通过openFileOutput()方法能够得到一个FileOutputStream对象
- 再借助它构建一个OutputStreamWriter对象
- 再使用OutputStreamWriter构建出一个BufferedWriter对象
- 最后通过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(); }
- 通过openFileInput()方法能够得到一个FileInputStream对象
- 再借助它构建一个InputStreamReader对象
- 再使用InputStreamReader 构建出一个BufferedReader对象
- 通过BufferedReader进行一行行读取,并存放在StringBuilder中,最后将读取到的内容返回即可