Android 用文件存储方式保存数据

文件存储是 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();
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值