Android中数据存储(一)

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

本文将为大家介绍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文件夹下的东西,清除数据,会清除整个包名目录下的东西

示例代码如下:

 1 public void read() {
 2         try {
 3             FileInputStream fis = openFileInput("demo.txt");
 4             byte[] buff = new byte[1024];
 5             int len = 0;
 6             if ((len = fis.read(buff)) != -1) {
 7                 System.out.println(new String(buff, 0, len));
 8             }
 9             fis.close();
10         } catch (FileNotFoundException e) {
11             e.printStackTrace();
12         } catch (IOException e) {
13             e.printStackTrace();
14         }
15     }
16     
17     public void write(){
18         try {
19             FileOutputStream fos = openFileOutput("demo.txt", MODE_PRIVATE);
20             fos.write("你若是感觉你有实力和我玩,良辰不介意奉陪到底 ".getBytes());
21             fos.close();
22         } catch (FileNotFoundException e) {
23             e.printStackTrace();
24         } catch (IOException e) {
25             e.printStackTrace();
26         }
27         
28     }

  使用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"/>

示例代码:

 1 public void write(){
 2             //判断sd卡状态
 3             if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)){
 4                 //创建file对象
 5                 File file = new File(Environment.getExternalStorageDirectory(), "info.txt");
 6                 try {
 7                     FileOutputStream fos = new FileOutputStream(file);
 8                     fos.write(("你若是感觉你有实力和我玩,良辰不介意奉陪到底").getBytes());
 9                     fos.close();
10                 } catch (Exception e) {
11                     e.printStackTrace();
12                 }
13             }
14             else{
15                 Toast.makeText(this, "你的SD卡不可用,良辰建议你检查一下", 0).show();
16             }
17             
18         }
19         
20         //读取
21         public void read(){
22             File file = new File(Environment.getExternalStorageDirectory(), "info.txt");
23             if(file.exists()){
24                 try {
25                     FileInputStream fis = new FileInputStream(file);
26                     //把字节流转换成字符流
27                     BufferedReader br = new BufferedReader(new InputStreamReader(fis));
28                     String text = br.readLine();
29                     System.out.println(text);
30                 } catch (Exception e) {
31                     e.printStackTrace();
32                 }
33             }
34         }

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

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

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

好了直接上代码。

 1 //获得SD卡总大小 
 2 private String getSDTotalSize() {  
 3     File path = Environment.getExternalStorageDirectory(); 
 4     //statfs 说他头发少 StatFs 一个模拟linux的df命令的一个类,获得SD卡和手机内存的使用情况  
 5     StatFs stat = new StatFs(path.getPath());  
 6     long blockSize = stat.getBlockSize();  
 7     long totalBlocks = stat.getBlockCount(); 
 8     //Formatter.formatFileSize()——一个区域化的文件大小格式化工具。 
 9     return Formatter.formatFileSize(MainActivity.this, blockSize * totalBlocks);  
10 }  
11 //获得sd卡剩余容量,即可用大小 
12 private String getSDAvailableSize() {  
13     File path = Environment.getExternalStorageDirectory();  
14     StatFs stat = new StatFs(path.getPath());  
15     long blockSize = stat.getBlockSize();  
16     long availableBlocks = stat.getAvailableBlocks();  
17     return Formatter.formatFileSize(MainActivity.this, blockSize * availableBlocks);  
18 }
19 //底层就是statfs,和上面结果一样  
20 long easy = Environment.getExternalStorageDirectory().getFreeSpace();
21 
22  //获得机身内存总大小
23 private String getRomTotalSize() {  
24     File path = Environment.getDataDirectory();  
25     StatFs stat = new StatFs(path.getPath());  
26     long blockSize = stat.getBlockSize();  
27     long totalBlocks = stat.getBlockCount();  
28     return Formatter.formatFileSize(MainActivity.this, blockSize * totalBlocks);  
29 }  
30 //获得机身可用内存 
31 private String getRomAvailableSize() {  
32     File path = Environment.getDataDirectory();  
33     StatFs stat = new StatFs(path.getPath());  
34     long blockSize = stat.getBlockSize();  
35     long availableBlocks = stat.getAvailableBlocks();  
36     return Formatter.formatFileSize(MainActivity.this, blockSize * availableBlocks);  
37 } 

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

二,使用SharedPreferences存储数据

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

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

  SharedPreferences存储步骤如下:

    1.通过context获取SharedPreferences对象。

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

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

    4.通过commit方法提交。

示例代码:

1    //往SharedPreferences存储数据
2         SharedPreferences sp = getSharedPreferences("config.txt", MODE_PRIVATE);
3         Editor edit = sp.edit();
4         edit.putString("name", "叶良辰");
5         edit.commit();
6         
7         //从SharedPreferences读取数据
8         String name = sp.getString("name", "");
9         Log.i("MainActivity", name);

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

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

原文地址:https://www.cnblogs.com/makaruila/p/4854557.html