Android中数据存储(一)

时间:2023-03-08 16:28:59

国庆没有给国家添堵,没有勾搭妹子,乖乖的写着自己的博客。。。。。

本文将为大家介绍Android中数据存储的五种方式,数据存储可是非常重要的知识哦。

一,文件存储数据

  ①在ROM存储数据

  关于在ROM读写文件,可以使用java中IO流来读写,但是谷歌很人性化,直接给你封装了一下,所以就有了Context提供的这两个方法:FileInputStream openFileInput(String name);

FileOutputStream openFileOutput(String name, int mode)。

  这两个方法第一个参数是文件名,第二个参数指定打开文件的模式。具体有以下四种:

   Context.MODEPRIVATE:为默认操作模式,代表该文件是私有数据,只能被应用本身访问,在该模式下,写入的内容会覆盖原文件的内容,如果想把新写入的内容追加到原文件中。可以使用Context.MODEAPPEND

   Context.MODE_APPEND:模式会检查文件是否存在,存在就往文件追加内容,否则就创建新文件。

   MODEWORLDREADABLE:表示当前文件可以被其他应用读取;
   MODEWORLDWRITEABLE:表示当前文件可以被其他应用写入。 如果希望文件被其他应用读和写,可以传入:
openFileOutput("demo.txt", Context.MODEWORLDREADABLE +Context.MODEWORLDWRITEABLE);

  使用这两个方法默认的存储位置/data/data/包名/files/...

-------------------------------------------------------------------------

在这顺便说一下,Linux文件的访问权限:

  示例:drwxrwxrwx

  r:读    w:写      x:执行

第1位:d表示文件夹,-表示文件
第2-4位:rwx,表示这个文件的所有者用户对该文件的权限
第5-7位:rwx,表示与文件所有者用户同组的用户对该文件的权限
第8-10位:rwx,表示其他用户组的用户对该文件的权限

-------------------------------------------------------------------------

此外,context还提供了其他几个方法: 

getFilesDir()得到的file对象的路径是data/data/包名/files
  存放在这个路径下的文件,只要你不删,它就一直在
getCacheDir()得到的file对象的路径是data/data/包名/cache
  存放在这个路径下的文件,当内存不足时,有可能被删除
系统管理应用界面的清除缓存,会清除cache文件夹下的东西,清除数据,会清除整个包名目录下的东西

示例代码如下:

 public void read() {
try {
FileInputStream fis = openFileInput("demo.txt");
byte[] buff = new byte[1024];
int len = 0;
if ((len = fis.read(buff)) != -1) {
System.out.println(new String(buff, 0, len));
}
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} public void write(){
try {
FileOutputStream fos = openFileOutput("demo.txt", MODE_PRIVATE);
fos.write("你若是感觉你有实力和我玩,良辰不介意奉陪到底 ".getBytes());
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} }

  使用openfileoutput()方法保存文件,文件是存放在手机里面的,存放一些小文件还行,但要是存放视频大文件,就需要在SD卡中进行存储了。

 ②在SD卡存储文件

  1.判断SD卡是否准备就绪。

if(Environment.getExternalStorageState()//用于获取SDCard的状态
.equals(Environment.MEDIA_MOUNTED))

  2.获取SD卡真实路径

Environment.getExternalStorageDirectory()//external 外部的 directory 目录

  3.使用IO流操作SD卡上的文件

注意:读写SD卡需要设置权限。

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

示例代码:

 public void write(){
//判断sd卡状态
if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
//创建file对象
File file = new File(Environment.getExternalStorageDirectory(), "info.txt");
try {
FileOutputStream fos = new FileOutputStream(file);
fos.write(("你若是感觉你有实力和我玩,良辰不介意奉陪到底").getBytes());
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
else{
Toast.makeText(this, "你的SD卡不可用,良辰建议你检查一下", 0).show();
} } //读取
public void read(){
File file = new File(Environment.getExternalStorageDirectory(), "info.txt");
if(file.exists()){
try {
FileInputStream fis = new FileInputStream(file);
//把字节流转换成字符流
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
String text = br.readLine();
System.out.println(text);
} catch (Exception e) {
e.printStackTrace();
}
}
}

平时在往SD卡或者ROM中存储大文件的时候,常常需要判断一下空间大小。接下来再为大家介绍一下如何获得存储设备剩余容量大小。

  首先你得知道这两个知识:

  • 存储设备会被分为若干个区块,每个区块有固定的大小
  • 区块大小 * 区块数量 等于 存储设备的总大小

好了直接上代码。

 //获得SD卡总大小
private String getSDTotalSize() {
File path = Environment.getExternalStorageDirectory();
//statfs 说他头发少 StatFs 一个模拟linux的df命令的一个类,获得SD卡和手机内存的使用情况
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
//Formatter.formatFileSize()——一个区域化的文件大小格式化工具。
return Formatter.formatFileSize(MainActivity.this, blockSize * totalBlocks);
}
//获得sd卡剩余容量,即可用大小
private String getSDAvailableSize() {
File path = Environment.getExternalStorageDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
return Formatter.formatFileSize(MainActivity.this, blockSize * availableBlocks);
}
//底层就是statfs,和上面结果一样
long easy = Environment.getExternalStorageDirectory().getFreeSpace(); //获得机身内存总大小
private String getRomTotalSize() {
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long totalBlocks = stat.getBlockCount();
return Formatter.formatFileSize(MainActivity.this, blockSize * totalBlocks);
}
//获得机身可用内存
private String getRomAvailableSize() {
File path = Environment.getDataDirectory();
StatFs stat = new StatFs(path.getPath());
long blockSize = stat.getBlockSize();
long availableBlocks = stat.getAvailableBlocks();
return Formatter.formatFileSize(MainActivity.this, blockSize * availableBlocks);
}

好了,终于把第一种讲完了,手为什么这么酸。。。。。。

二,使用SharedPreferences存储数据

  首先介绍一下SharedPreferences,有一个姑娘,她有一些任性,还有一些嚣张。(⊙o⊙)…走神了。。。。

  SharedPreferences是Android平台上一个轻量级的存储类,主要保存一些常用的配置信息。它的本质是基于xml文件存储Kay-value键值对数据。

  SharedPreferences存储步骤如下:

    1.通过context获取SharedPreferences对象。

    2.利用SharedPreferences的edit方法获取Editor对象。

    3.通过Editor对象存储key-value键值对数据

    4.通过commit方法提交。

示例代码:

    //往SharedPreferences存储数据
SharedPreferences sp = getSharedPreferences("config.txt", MODE_PRIVATE);
Editor edit = sp.edit();
edit.putString("name", "叶良辰");
edit.commit(); //从SharedPreferences读取数据
String name = sp.getString("name", "");
Log.i("MainActivity", name);

使用SharedPreferences会把数据存储在/data/data/<package name>/shared_prefs

温馨提示:篇幅有点大,请移步。。。。。(还没写,写完之后会贴出来)。