数据存储(SharedPreferences)(内部存储及外部存储)

作用 :

处理将数据存储到本地的操作

注意:

本地指的不是d盘,f盘,而是手机的机身内存和外部存储卡

控制数据存储,取出的方式:

  1. SharedPreferences
  2. 内部存储
  3. 外部存储
    (内部存储和外部存储合起来也可称为文件存储)
  4. 网络(即数据存储服务端中,客户端想要读取数据需连网)
  5. SQLite数据库

(1)SharedPreferences 轻量级存储

特点:

1.生成的本地存储文件的类型固定为xml类型
2.用于存储多组键值对数据
3.文件存储位置固定: data/data/程序包名/shared-prefs文件夹内
4.能够存储的数据类型有限:String,Boolean,Long,Int,Float,Set<String>

使用方式:

存储数据:

 /*
         * 初始化SharedPreferences对象
         *  方式一:通过getPreferences方法获取对象
         *  方式二:通过getSharedPreferences方法获取对象
         *  两者的区别:通过getPreferences方法获取的对象存储数据后生成的文件的文件名称是固定的,不能自定义
         *  通过getSharedPreferences方法获取对象可以指定生成的文件的名称
         *  参数:
         *  1. String 类型,用于设置文件名称
         *  2.int 类型,用于设置生成的文件的文件模式(如只读,只写,私有等)
         * */
        pref = getSharedPreferences("abc", Context.MODE_PRIVATE);
    }


    public void click (View v) {
        switch (v.getId()) {
        case R.id.but_save:


            //通过pref对象获取Editor对象,用于通过此对象调用方法设置要写入的数据
             Editor editor = pref.edit();
             //添加要写入的数据
             editor.putString("str", "我是string");
             editor.putBoolean("boo", true);
             editor.putInt("int", 25);

             //提交,只有提交后数据才能真正的写入到本地文件中
             //可以使用commit方法或者apply方法
             editor.commit();

取出数据:

//取出数据
            /*
             *通过get***方法读取数据
             *参数:
             *1: 要读取的数据对应的key
             *2: 默认值,当文件不存在获取文件存在但是key写错了时,方法的返回值就是参数指定的默认值
             * 
             */
            String s = pref.getString("str", "default");
            int num = pref.getInt("int", 18);
            boolean f = pref.getBoolean("boo", false);

            Log.i("oye", "读取出数据 :  "+s+"  "+num+"  "+f);

备注:可通过同一个pref对象同时控制数据的存储和取出操作

想要清空通过SharedPreferences存储的内容:

//清空pref中的数据
pref.edit().clear().commit();

(2)文件存储:

统一特点:

  1. 可以在指定位置存储一个任意类型的文件
  2. 使用io流控制数据的存储和读取

    文件存储中可以细分为两种:内部存储(Internal Storage)和外部存储(External Storage)
    
    两者区别在于:存储位置的基本路径.
    
    (1)内部存储的存储基本路径为:data/data/程序包名/files/文件夹中
    (2)外部存储的基本路径为:sd卡中(外部存储卡) /mnt/sdcard
    

内部存储的使用:

存储数据:

//获取output流,用于稍后的写入数据操作
            try {
                FileOutputStream fos = openFileOutput("nei.txt", Context.MODE_PRIVATE);
                //写入数据
                fos.write("东方isUFO速度否阿萨德ofUI阿萨帝欧富欧式度".getBytes());

                fos.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

取出数据:

try {
                FileInputStream fis = openFileInput("nei.txt");

                byte[] b = new byte[2048];
                int num = -1;
                StringBuffer sb = new StringBuffer();

                while((num = fis.read(b)) != -1) {
                    sb.append(new String(b,0,num));
                }

                Log.i("oye", "内部存储中存储的数据位:"+sb.toString());

            } catch (FileNotFoundException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

外部存储的使用:

存储数据:

File file = new File("/mnt/sdcard/ay1610");
            if (!file.exists()) {  //判断是否存在
                file.mkdirs();  //创建文件夹
            }
            try {
                FileOutputStream fosw = new FileOutputStream("/mnt/sdcard/ay1610/wai.txt");

                fosw.write("dfojodifosduifosdaiufodsufoasdufoiadsufoasdufiasdf ".getBytes());

                fosw.close();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

取出数据:

FileInputStream fisw = new FileInputStream("/mnt/sdcard/ay1610/wai.txt");
                byte[] b = new byte[2048];
                int num = -1;
                StringBuffer sb = new StringBuffer();

                while((num = fisw.read(b)) != -1) {
                    sb.append(new String(b,0,num));
                }

                Log.i("oye", "外部存储中存储的数据为为为:::"+sb.toString());
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

向文件存储中写入BItmap图片数据:

Bitmap bit = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);

            FileOutputStream fos = null;
            try {
                fos = new FileOutputStream("/mnt/sdcard/ay1610/ic.png");
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            //  写入Bitmap图片数据
            /**
             * 通过compress方法将bit中的数据压缩到参数3指定的output流中
             * 1: 图片压缩时使用的格式
             * 2: 图片压缩时的质量,范围:0到100,质量数越高图片越清晰
             * 注:如果压缩格式时png,那么质量写多少都无影响
             * 当此方法执行完毕后,即可在fos对应的路径中生成一张图片对象
             */
            bit.compress(CompressFormat.PNG, 100, fos);

从文件存储中取出图片并显示:

//当想要让imageView上显示文件存储中的图片时
            //方式一:
//          Bitmap bitm = BitmapFactory.decodeFile("/mnt/sdcard/ay1610/ic.png");
//          iv.setImageBitmap(bitm);

            //方式二:
            iv.setImageURI(Uri.parse("file:///mnt/sdcard/ay1610/ic.png"));

关于sd卡操作的常用方法:

public class SdCardUtils {

    // 判断sd卡是否正常挂载
    public boolean isSdNormal() {
        /**
         * 通过Environment.getExternalStorageState()方法获取当前设备上sd卡的状态
         * 此方法的返回值是一个String类型的数据 Environment.MEDIA_MOUNTED 代表sd卡正常挂载
         */
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    // 获取当前设备上sd卡的根目录
    public File getSdFile() {

        return Environment.getExternalStorageDirectory();
    }

    // 获取当前设备上sd卡的根目录 对应的String路径
    public String getSdPath() {
        return Environment.getExternalStorageDirectory().getAbsolutePath();
    }

    // 获取指定数据类型的文件夹的具体路径。如:获取照片文件夹的具体路径
    public String getZhiPath(String type) {
        return Environment.getExternalStoragePublicDirectory(type)
                .getAbsolutePath();
    }

    // 获取sd卡的总大小
    public String getTotalSize(Context context) {
        // 获取SD卡根目录
        File path = Environment.getExternalStorageDirectory();
        // 获取指定目录下的内存存储状态
        StatFs stat = new StatFs(path.getPath());
        // 获取单个扇区的大小
        long blockSize = stat.getBlockSize();
        // 获取扇区的数量
        long totalBlocks = stat.getBlockCount();

        // 总空间 = 扇区的总数 * 扇区的大小
        long totalSize = blockSize * totalBlocks;
        // 格式化文件大小的格式
        return Formatter.formatFileSize(context, totalSize);
    }

    // 获取sd卡的可用大小
    public String getAvaliSize(Context context) {
        // 获取SD卡根目录
                File path = Environment.getExternalStorageDirectory();
                // 获取指定目录下的内存存储状态
                StatFs stat = new StatFs(path.getPath());
                // 获取单个扇区的大小
                long blockSize = stat.getBlockSize();

                // 获取可以使用的扇区数量
                long availableBlocks = stat.getAvailableBlocks();
                // 可用空间 = 扇区的大小 + 可用的扇区
                long availableSize = blockSize * availableBlocks;

                // 格式化文件大小的格式
                return Formatter.formatFileSize(context, availableSize);
    }
}
发布了34 篇原创文章 · 获赞 3 · 访问量 3万+

猜你喜欢

转载自blog.csdn.net/The_king_of_Asia/article/details/54849100