//将数据存储到文件中 (文件默认存储到:/data/data/<packagename>/files/ 目录下)
openFileOutput(),第一个参数是文件名,第二个参数是文件的操作模式, 主要有两种模式可选,MODE_PRIVATE 和MODE_APPEND。其中MODE_PRIVATE 是默认的操作模式,所写入的内容将会覆盖原文件中的内容,而MODE_APPEND 则表示如果该文件已存在就往文件里面追加内容。
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();
}
}
}
//从文件中读取数据
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();
}