Android 基础-3.0 数据存储方式

Android几种数据存储方式

  1. 文件存储
  2. SharedPreference存储
  3. Json解析
  4. SQLite数据库存储

文件存储

文件存储是Android中最基本的一种存储方式,和Java中实现I/O的方式,由Context类提供openFileInput()和openFileOutput()方法打开。文件存储主要分两种存储,一种是内部存储,一种是外部存储。

内存存储:使用了FileInputStream类中的openFileInput()方法,用于读取数据;使用了FileOutputStream类中的openFileOutput()方法,用于写入数据。

外部存储:使用Enviroment类中的getExternalStorageDirectory()方法对外部存储上的文件进行读写。

内存存储-写入文件

                File file = new File(this.getFilesDir(), "info.txt");
                try {
                    FileOutputStream fos = new FileOutputStream(file);
                    String info = qq + "##" + password;
                    fos.write(info.getBytes());
                    fos.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

内存存储-读取文件

    /**
     * 根据原来保存的文件信息,把QQ号码和密码信息显示到界面
     */
    private void restoreInfo() {
        File file = new File(this.getFilesDir(), "info.txt");
        // 如果文件存在并且有内容就读取出来
        if (file.exists() && file.length() > 0) {
            try {
                FileInputStream fis = new FileInputStream(file);
                BufferedReader br = new BufferedReader(new InputStreamReader(fis));

                String info = br.readLine();
                String qq = info.split("##")[0];
                String pwd = info.split("##")[1];
                mEtnumber.setText(qq);
                mEtPasswd.setText(pwd);

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

外部存储

外部存储,指的是写入到手机SD卡。需要两个3个步骤
1、AndroidManifest.xml 申请权限
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
2、在调用的地方,注册 Manifest.permission.WRITE_EXTERNAL_STORAGE 权限
3、调用的地方,需要检查SD卡可用状态 Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
    /**
     * 模拟向SD卡写入一个视频文件
     * @param view
     */
    public void click(View view) {
        performCodeWithPermission("写入文件到sd卡", new PermissionCallback() {
            @Override
            public void hasPermission() {
                // 检查SD卡的状态
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    File sdFile = Environment.getExternalStorageDirectory();// 外部存储空间
                    long sdSize = sdFile.getFreeSpace();
                    if (sdSize > 5 * 1024 * 1024) {// 5M
                        File file = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + "hlw.3gp");
                        try {
                            FileOutputStream fos = new FileOutputStream(file);
                            byte[] buffer = new byte[1024];
                            for (int i = 0; i < 5 * 1024; i++) {
                                fos.write(buffer);
                            }
                            fos.close();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    } else {
                        Toast.makeText(MainActivity.this,"sd卡空间不足", Toast.LENGTH_SHORT).show();
                    }
                } else {
                    Toast.makeText(MainActivity.this,"没有挂载", Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void noPermission() {

            }
        }, Manifest.permission.WRITE_EXTERNAL_STORAGE);
    }
}

SharedPreference存储

对用户输入的账号以及密码进行存储,并且进行显示。我们使用SharedPreferences

存储数据

/**
     * 保存用户名 密码的业务方法
     * @param context 上下文
     * @param username 用户名
     * @param pas 密码
     * @return true 保存成功  false 保存失败
     */
    public static void saveUserInfo(Context context,String username,String pas){
        /**
         * SharedPreferences将用户的数据存储到该包下的shared_prefs/config.xml文件中,
         * 并且设置该文件的读取方式为私有,即只有该软件自身可以访问该文件
         */
        SharedPreferences sPreferences=context.getSharedPreferences("config", context.MODE_PRIVATE);
        Editor editor=sPreferences.edit();
        //当然sharepreference会对一些特殊的字符进行转义,使得读取的时候更加准确
        editor.putString("username", username);
        editor.putString("password", pas);
        //这里我们输入一些特殊的字符来实验效果
        editor.putString("specialtext", "hajsdh><?//");
        editor.putBoolean("or", true);
        editor.putInt("int", 47);
        //切记最后要使用commit方法将数据写入文件
        editor.commit();
    }

读取数据

 //显示用户此前录入的数据
    SharedPreferences sPreferences=getSharedPreferences("config", MODE_PRIVATE);
    String username=sPreferences.getString("username", "");
    String password =sPreferences.getString("password", "");
    ed_username.setText(username);
    ed_pasw.setText(password);

显示的XML

<?xml version='1.0' encoding='utf-8' standalone='yes' ?>
<map>
<string name="specialtext">hajsdh&gt;&lt;?//</string>
<string name="username">dsa</string>
<string name="password">dasdasd</string>
<int name="int" value="47" />
<boolean name="or" value="true" />
</map>

 JSON读取

        // 创建Json
       JSONObject jsonObject = new JSONObject();
       try {
           jsonObject.put("name", "jadyli");
           jsonObject.put("gender", "male");
           jsonObject.put("age", 18);
           System.out.println(jsonObject.toString(1));
       } catch (JSONException e) {
           e.printStackTrace();
       }

        // 解析Json
        String json = "{"name": "jadyli", "gender": "male", "age": 18}";
        try {
            JSONObject jsonObject = new JSONObject(json);
            System.out.println("姓名:" + jsonObject.getString("name"));
            System.out.println("性别:" + jsonObject.getString("gender"));
            System.out.println("年龄:" + jsonObject.getString("age"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
原文地址:https://www.cnblogs.com/jys509/p/11077797.html