文件存储是 Android 中最基本的一种数据存储方式,它不对存储的内容进行任何的格式化处理,所有数据都是原封不动地保存到文件当中的,因而它比较适合用于存储一些简单的文本数据或二进制数据。
写文件数据
1.创建FileOutPutStream对象
FileOutPutStream out = openFileOutput("文件名",Context.模式);
模式的说明:MODE_PRIVATE 是默认的操作模式,表示当指
定同样文件名的时候,所写入的内容将会覆盖原文件中的内容,而 MODE_APPEND 则表示如果该文件已存在就往文件里面追加内容,不存在就创建新文件。
文件名不可以包含路径,因为所有的文件都是默认存储到/data/data/packagename/files/ 目 录 下 的 。
2.创建BufferedWriter对象
BufferedWriter Writer = new BufferedWriter(new OutputStreamWriter(out)
3.写
Writer.writer("你要写入的内容")
4.结束后关闭
Writer.close()
完整代码:
public void save() {
String data = "Data to save";
FileOutputStream out = null;
BufferedWriter writer = null;
try {
out = openFileOutput("data", Context.MODE_PRIVATE);
writer = new BufferedWriter(new OutputStreamWriter(out));
writer.write(data);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
if (writer != null) {
writer.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
读文件数据
1.创建FileInputStream对象
FileInputStream in = openFileInput("文件名");
2.创建BufferedReader对象
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
3.(可选)创建一个StringBuilder来接收文本数据
StringBuilder content = new StringBuilder();
String line = "";
while ((line = reader.readLine()) != null) {
content.append(line);
}
完整代码
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();
}