温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

android笔记

发布时间:2020-10-23 03:43:34 来源:网络 阅读:356 作者:yahaa 栏目:移动开发

14.3.01


数据存储(持久化)  

五种:(外存)

1Shared Preferences

Store private primitive data in key-value pairs.

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

2Internal Storage

Store private data on the device memory.

内部存储

3External Storage

Store public data on the shared external storage.

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

4SQLite Databases

Store structured data in a private database.

数据库存储(外存)

5Network Connection

Store data on the web with your own network server.

网络存储



1、sharePreferences

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


例子:按钮点击保存

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

   SharePreferences preference=getPreferences(0);//0:默认值

//编辑器类型的对象

Editor edit=Preference.edit();

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

Edit.putBoolean(isLogin,true);

edit.putString(name,Lucy);

//提交

   Commit();



获取数据

getBoolean(isLogin,false);//false:默认值

getString(name,SS);//SS:默认值

   privatevoid getData() {

   SharedPreferences preferences = getPreferences(0);

   boolean login = preferences.getBoolean("isLogin", false);

   String name = preferences.getString("name", "Lily");

   mTv_show.setText(login+"  "+name);

}


保存位置

Data/data/包名/shared_prefs/xxx.xml

修改保存位置:

Sharepreferences sp=getSharepreferrences(xibo,0);//xibo保存的文件名





2、InternalStorage

保存位置:

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

保存


privatevoid saveData() {

FileOutputStream openFileOutput =null;

try {

openFileOutput = openFileOutput("aa.txt", MODE_PRIVATE);

String str="Hello";

openFileOutput.write(str.getBytes());

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally{

if(openFileOutput!=null){

try {

openFileOutput.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}



读取

FileInputStream

privatevoid getData() {

FileInputStream fis=null;

ByteArrayBuffer bab=new ByteArrayBuffer(4000);

try {

Log.e("getData", "sss");

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

int len;

byte[] buffer=newbyte[1024];

while(-1!=(len=fis.read(buffer))){

bab.append(buffer, 0, len);

}

String str=new String(bab.toByteArray(), 0, bab.length());

mTv_show.setText(str);  

Log.e("getData------>", ""+bab.length());

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally{

if(fis!=null){

try {

fis.close();

} catch (IOException e) {

e.printStackTrace();

}

}

}

}


读写模式:

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

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

MODE_WORLD_READABLE其他应用可读

MODE_WORLD_WRITEABLE其他应用可写


3、外部读取


查找sd

   File file =Environment.getExternalStorageDirectory();

   String path=file.getAbsolutePath();

判断sd卡是否可用

Environment..MEDIA_MOUNTED.equals(Environment.getExternalStorageState());

获得sd卡的可用空间

file.getFreeSpace();


 

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI