天天看点

数据存储(持久化)

14.3.01

数据存储(持久化)  

五种:(外存)

1、shared preferences

store private primitive data in key-value pairs.

参数共享(保存关键参数:下载、登陆等)

2、internal storage

store private data on the device memory.

内部存储

3、external storage

store public data on the shared external storage.

外部存储(保存文件、安装包)

4、sqlite databases

store structured data in a private database.

数据库存储(外存)

5、network connection

store data on the web with your own network server.

网络存储

1、sharepreferences

应用场景:应用程序有少量的数据需要保存(设置参数的保存)

例子:按钮点击保存

//得到参数共享类型的对象

   sharepreferences preference=getpreferences(0);//0:默认值

//编辑器类型的对象

editor edit=preference.edit();

//想编辑器对象添加数据

edit.putboolean(“name”);

//提交

   commit();

获取数据

getboolean(“name”);//ss:默认值

   sharedpreferences preferences = getpreferences(0);

   string name = preferences.getstring("name", "lily");

}

保存位置

data/data/包名“xibo<span style=\"\\"font-size:14px;font-family:'times\">”,0);//xibo保存的文件名

2、internalstorage

保存位置:

data/data/包名/files/aa.txt"

保存

fileoutputstream openfileoutput =null;

openfileoutput = openfileoutput("aa.txt", mode_private);

openfileoutput.write(str.getbytes());

e.printstacktrace();

if(openfileoutput!=null){

openfileoutput.close();

读取

fileinputstream

fileinputstream fis=null;

try {

fis=new fileinputstream("data/data/com.example.day_example/files/aa.txt");

byte[] buffer=newbyte[1024];

bab.append(buffer, 0, len);

string str=new string(bab.tobytearray(), 0, bab.length());

log.e("getdata------>", ""+bab.length());

if(fis!=null){

fis.close();

读写模式:

mode_private私有模式:只有当前应用才能对这个文件进行读写操作,不会进 行叠加,每次都清空

mode_append添加模式:只有当前应用才能对这个文件进行读写操作,对数据  追加

mode_world_readable其他应用可读

mode_world_writeable其他应用可写

3、外部读取

查找sd卡是否可用

environment..media_mounted.equals(environment.getexternalstoragestate());

获得