安卓 SharedPreferences存储+SD卡存储

SharedPreferences

SharedPreferences简称Sp(后面都会称Sp),是一种轻量级的数据存储方式,采用Key/value的方式 进行映射
在手机的/data/data/package_name/shared_prefs/目录下以xml的格式存在

写数据

java代码

 @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //写数据
        SharedPreferences sp = getSharedPreferences("login", MODE_PRIVATE);
        SharedPreferences.Editor edit = sp.edit();
        edit.putString("name","黑子");
        edit.putInt("age",18);
        edit.putFloat("num",3.5f);
        edit.putBoolean("isman",false);
        edit.putLong("id",1424242422);
        edit.commit();
    }

点击右下角的devices找data/data下项目名你自己起名字.xml

读数据

java代码

 //读数据
    private void read() {
        //得到SharedPreferences对象
        //参数一 xml文件的名字 参数二 模式 MODE_PRIVATE 指定该SharedPreferences数据只能被本应用程序读写
        SharedPreferences preferences = getSharedPreferences("sgf", MODE_PRIVATE);
        //直接读取
        //参数一 键  参数二 找不到的时候给默认值
        String name=preferences.getString("name","");
        int age=preferences.getInt("age",0);
        boolean isman=preferences.getBoolean("isman",false);
        float num=preferences.getFloat("num",0.0f);
        long id=preferences.getLong("id",0l);
        Toast.makeText(this, name+":"+age+":"+isman+":"+num+":"+id, Toast.LENGTH_SHORT).show();
    }

内部文件存储

openFileOutput

与java 操作文件没有区别.只是路径是唯一的

 FileOutputStream fileOutputStream = null;
                try {
                    fileOutputStream = openFileOutput("aa.json", MODE_PRIVATE);
                    fileOutputStream.write("hello".getBytes());
                    fileOutputStream.flush();
                    fileOutputStream.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

openFileInput

与java 操作文件没有区别.只是路径是唯一的

FileInputStream fileInputStream = null;
        try {
            fileInputStream= openFileInput("aa.json");
            byte[] b = new byte[1024];
            int len = 0;
            while((len = fileInputStream.read(b)) != -1){
                Log.i(TAG, "onClick: "+new String(b,0,len));
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值