Android下数据存储

Android下数据存储方式:
1.文件
2.SharedPreferences(维护的是一个xml文件)
3.SQLite数据库
4.ContentProvider内容提供者
5.网络

===============================================
文件存储:

1.保存数据到手机内存(用户名和密码)
String path = “/data/data/com.qqdemo<包名>/userinfo.txt”;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(path);
String info = name+”##”+pwd;
fos.write(info.getBytes());
fos.flush();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}

避免包名改变的时候,出现问题,采用如下方式:
/data/data/包名/files
String fileDir = context.getFilesDir();
File file = new File(fileDir, “userinfo.txt”);
FileOutputStream fos = new FileOutputStream(file);

/data/data/包名/cache :保存在缓存中
context.getCacheDir();

获取数据:
/data/data/<包名>/files/userinfo.txt
FileOutputStream fos = openFileOutput(“userinfo.txt”, Context.MODE_PRIVATE); // 私有文件(其他应用程序无法访问)
Context.MODE_WORLD_READABLE // 可读 (其他应用程序无法写)
Context.MODE_WORLD_WRITEABLE) // 可写 (其他应用程序无法读)
Context.MODE_WORLD_READABLE + Context.MODE_WORLD_WRITEABLE // 可读可写 (其他应用程序可读可写)

查看文件:
drwxrwx–x
-rw-rw—-


第1位:代表文件的类型(d:表示文件夹;-:表示文件;l:表示挂载某一个文件)
第2-4位:rw-:表示当前用户的权限 110 - 6 (-:表示0,其他表示1)
第5-7位:当前用户所在组的其他组员权限
第8-10位:其他所有人的权限 (—:表示没有任何权限;r–:表示可读;-w-:表示可写;rw-:表示可读可写)

2.保存数据到sd卡 /mnt/sdcard/userinfo.txt

(1)先判断当前的手机是否有sdcard:
String state = Environment.getExternalStorageState();
if(!Environment.MEDIA_MOUNTED.equals(state)){
// 没有挂载sdcard
}

(2)获得sdcard内存状态:
File sdcardFileDir = Environment.getExternalStorageDirectory();
String path = sdcardFileDir.getPath();

获得手机内部(系统)存储空间的状态:
// 手机内部存储根目录:
File dataFileDir = Environment.getDataDirectory();
String path = dataFileDir.getPath();

// 获得磁盘状态对象
StatFs statFs = new StatFs(path);
// 获得总内存
statFs.getTotalBytes();
// 获得可用内存
statFs.getAvailableBytes();

(3)File sdcardDir = Environment.getExternalStorageDirectory();
File file = new File(sdcardDir, “userinfo.txt”);

添加向外部存储设备读写的权限:

==========================================================================================
偏好设置SharedPreferences:

存储路径:
/data/data/包名/shared_prefs/

SharedPreferences sp = context.getSharedPreferences(“userinfo.txt”, Context.MODE_PRIVATE);
Editor editor = sp.edit();
editor.putString(“name”, name);
editor.commit();

===========================================================================================
内容提供者ContentProvider (跨进程访问数据)

1.创建一个类MyContentProvider 继承自 ContentProvider
2.在配置文件中注册

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值