您的位置:首页 > 移动开发 > Android开发

android数据存储:数据持久化的文件存储

2017-09-26 14:09 309 查看
//将数据存储到文件中 (文件默认存储到:/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();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: