Content类提供了openFileOutput()方法,可以将数据存储到指定的文件中。这个方法接收两个参数:
文件名 文件是默认存放在 /data/data/<packagename>/file/ 目录下的
文件的操作模式 主要有两种操作模式:MODE_PRIVATE 覆盖原文件内容; MODEAPPEND在原文件中追加内容
FileOutputStream out = null; BufferedWriter writer = null; try { //存储的文件名为data,操作模式为覆盖原文件 out = openFileOutput("data", MODE_PRIVATE); writer = new BufferedWriter(new OutputStreamWriter(out)); writer.write(inputText); } catch (IOException e) { e.printStackTrace(); } finally { if(writer != null) { try { writer.close(); } catch (IOException e) { e.printStackTrace(); } } }同样的,Content类也提供了一个 openFileInput的方法来读取数据,只接收一个参数,就是文件名,它会自动到/data/data/<packagename>/file/目录下读取数据,并返回一个FileInputStream对象,然后通过Java的IO流将数据读取出来。
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(); } } }参考《第一行代码》