数据存储方式
Android平台提供了五种数据存储的方式:
- 文件存储:Android提供了openFileInput()和openFileOutput()方法来读取设备上的文件,读取方式和Java中的I/O程序是一样的。
- SharedPreferences:可以用来存储简单的配置信息,是用的XML格式将数据存储到设备中。
- SQLite数据库:这个是Android自带的一个轻量级数据库。
- ContentProvider:Android四大组件之一,主要应用于应用程序之间的数据交换。
- 网络存储:将数据存储到云服务器上,通过网络提供的存储空间来存储数据。
文件存储
这里主要讲解内部存储,就是将数据以文件的形式存储到应用中。
内部存储使用的是Context提供的openFileInput()和openFileOutput()方法,示例:
FileOutputStream out = openFileOutput(String name, int mode);
FileInputStream in = openFileInput(String name);
上述代码中,openFileOutput方法是用于将数据存储到相应的文件,openFileInput方法是将数据从文件读取到应用程序中(这里如果分不清的话可以这么记住:我们的视角始终是站在应用程序这边,将数据从我们这写到对面文件中就是out,将数据从对面文件拿回到我们这就是in)。mode表示文件的操作模式,常用的就两种:MODE_PEIVATE,MODE_APPEND。前一种是表示该文件只能被当前程序读写,而且数据是会被覆盖的;后一种表示该文件可以追加。
存储数据示例:
private String fileName = "data.text"; //文件的名称
private String content = "helloWorld!"; //要保存的内容
FileOutputStream out = null;
try {
out = openFileOutput(fileName, MODE_PRIVATE);
out.write(content.getBytes()); //将数据写入对应文件中
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if (out != null) {
try {
out.close(); //关闭流
} catch (IOException e) {
e.printStackTrace();
}
}
}
读取数据示例:
private String fileName = "data.text"; //文件的名称
private String content = ""; //要读出的内容
FileInputStream in = null;
try {
in = openFileInput(fileName);
byte[] buffer = new byte[in.available()]; //创建缓冲区,并获取文件长度
in.read(buffer); //读取文件内容到缓冲区
content = new String(buffer); //转换成字符串
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally{
if (in != null) {
try {
in.close(); //关闭流
} catch (IOException e) {
e.printStackTrace();
}
}
}
SharedPreferences
当程序中有一些少量数据需要持久化存储时,可以使用SharedPreferences进行存储,包括用户名,密码,一些配置信息等。
数据存入
大致的步骤有获取SharedPreferences示例,获取编辑器对象,写入数据,提交数据四个步骤。
SharedPreferences sp = getSharedPreferences(fileName,MODE_PRIVATE); //获取实例对象
SharedPreferences.Editor editor = sp.edit(); //获取编辑器对象
editor.putString("name","value"); //存入数据
editor.commit(); //提交数据
数据读取与删除
读取数据主要有两步:获取实例对象,获取数据
SharedPreferences sp = getSharedPreferences(fileName,MODE_PRIVATE); //获取实例对象
String data = sp.getString("name",""); //获取数据
需要注意的是,getXXX()方法的第二个参数为缺省值,如果sp中不存在该key那么返回缺省值。
删除数据
editor.remove("name"); //删除一条数据
editor.clear(); //删除所有数据