Android文件存取与SharedPreferences

文件读取
//把inputText存入一个叫data的文件中
FileOutputStream out = null;
BufferedWriter writer  = null;
out  = openFileOutput("data",Context.MODE_PRIVATE);
writer.write(inputText);

//从data文件读取数据
FileInputStream in = null;
BufferedReader reader = null;
StringBuilder content = new StringBuilder();
in = openFileInput("data");//获得数据流
reader = new BufferedReader(new InputStreamReader(in));//读取数据
String line;
while((line = reader.readLine())!=null)//一行一行的读取
{
  content.append(line);//一行一行地加进去
}


SharePreferences
存放位置在/data/data/<package name>/shared_prefs/
主要有一下3种用法
1.Context类的getSharePreferences()方法
接收两个参数
第一个参数指定SharePreferences文件的名称,如过不存在就创建一个
第二个参数指定操作模式,只有MODE_PRIVATE
2.Acitvity类的getPreferences()方法
只有一个参数:指定操作模式,只有MODE_PRIVATE     
自动将当前活动类名作为SharedPreferences的文件名
3.PreferenceManager类的getDefaultSharedPreferences()方法
自动使用当前应用程序的包名作为前缀命名SharedPreferences文件

实现方法
1.调用方法edit()方法获得一个SharedPreferences.Editor对象
2.向SharedPreferences.Editor对象  例如: editor.putString()
3.调用commit()方法将添加的数据提交,完成数据储存
实例:封装成一个pustData方法(Context方法)
    //数据都存放以LOGIN命名的SharePreferences中
    public static final String LOGIN = "loginDate";

    /**
     * 把账号和密码存入SharedPreferences中
     * @param context
     * @param id
     * @param password
     */
    public static void putData(Context context,String id, String password)
    {
        SharedPreferences.Editor editor = context.getSharedPreferences(LOGIN,MODE_PRIVATE).edit();
        editor.putString("id",id);
        editor.putString("password",password);
        editor.apply();
    }
如上面代码,我从LoginActivity中调用putData个方法就需要把Context传过去,在把String的一些值都put上去,除了putString ,其他的类似putInt()等等都可以实现
最后记得apply();
读取方法
读取的方法虽然事一样的道理,但还是有点不同,我们在调用封装的时候一般事先通过context.getSharedPreferences,但如果就在Activity中就可以省掉Activity了,上面的获取editor也是一样
实例:一个封装的getData方法
    /**
     * 把对应的数据从SharedPreferences取出来
     * @param context
     * @param data
     * @return
     */
    public static String getData(Context context,String data)
    {
        SharedPreferences sharedPreferences = context.getSharedPreferences(LOGIN,MODE_PRIVATE);
        return sharedPreferences.getString(data,"");
    }
对于其他类例如:int boolean就类似的扩展
example :   boolean married = pref.getBoolean("married",false);

清除方法
非常简单,一看就懂
    /**
     * 清理SharedPreferences
     * @param context
     */
    public static void  clear(Context context)
    {
        SharedPreferences sharedPreferences = context.getSharedPreferences(LOGIN,MODE_PRIVATE);
        SharedPreferences.Editor editor = sharedPreferences.edit();
        editor.clear();
        editor.apply();
    }
这些内容基本上是简单总结了郭霖的《第一行代码》,有资源可以去看书,非常不错的一本书

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值