• 关于缓存你了解多少(二)


    哈哈,按照惯例,没图说个JJ啊?

    老子说,一生二,二生三,三生万物。(万物生长,哈哈)

    好吧,言归正传,之前一位师兄对我说,不懂就查嘛,查不到就问嘛,问不到在“靠!"嘛,

    有道理,先查,

    项目中涉及到缓存,想把一个json字符串解析之后获取的url 集合缓存下来,因为SharedPreferences没有存储数组的方法所以只能将其序列化,

    SharedPreferences 

    >1 存储字符串:

    思路:根据Context获取SharedPreferences对象,利用edit()方法获取Editor对象,通过Editor对象存储key-value键值对数据

    最后,通过commit()方法提交数据

    如:在acitivity onCreate()方法中

     //获取SharedPreferences对象
           Context ctx = MainActivity.this; //获取上下文       
           SharedPreferences sp = ctx.getSharedPreferences("shared_file", MODE_PRIVATE);
           //存入数据
           Editor editor = sp.edit();
           editor.putString("OneBelowZero", "string");
           editor.putInt("INT_KEY", 0);
           editor.putBoolean("Flag", true);
           editor.commit();
     
       //log方式返回OneBelowZero的值
           Log.d("shared_file", sp.getString("OneBelowZero", "none"));
           //如果Flag不存在,则返回值为"none"
           Log.d("shared_file", sp.getString("Flag", "none"));
    接下来取数据:
      同样
      SharedPreferences sp = ctx.getSharedPreferences("shared_file", MODE_PRIVATE);

      sp.getString("OneBelowZero", "");//默认值不用管
        sp.getBoolean("Flag", true);

    >ok,有人问村一个map集合怎么办啊? 变通一下呗!

    为了代码的简洁。先创建一个工具类用于存取集合

    package com.example.cacheutil.sp;

    import java.util.HashMap;
    import java.util.Map;

    import com.example.cacheutil.MainActivity;

    import android.content.Context;
    import android.content.SharedPreferences;
    import android.content.SharedPreferences.Editor;

    public class SharedpreUtil {

        private Context context;

        public SharedpreUtil(Context context) {
          this.context = context;
        }

      /**
      * 保存参数
      */
      public void save(String path,String girl, int age) {
        SharedPreferences preference = context.getSharedPreferences(path,
                Context.MODE_APPEND);// 得到SharedPreference對象对象
        Editor editor = preference.edit(); // 得到edit编译器
        editor.putString("girl", girl);
        editor.putInt("age", age);
        // 提交之后才写入xml中,不提交只是在缓存中而已
        editor.commit();
      }

      /**
      * 显示参数
      */
      public Map<String, String> put() {
        Map<String, String> map = new HashMap<String, String>();
        SharedPreferences preference = context.getSharedPreferences(MainActivity.path,
                  Context.MODE_APPEND);
        map.put("name", preference.getString("name", ""));
        map.put("age", String.valueOf(preference.getInt("age", 0)));
        return map;
        }

    }

    ======================================

    相信聪明的你一定被我一语点醒你梦中情人啊!

    public class MainActivity extends Activity {

        private EditText OneBelowZero;
        private EditText One;
        public static String path="shared_file";
        private SharedpreUtil perf;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);


          OneBelowZero = (EditText) findViewById(R.id.et_str);
          One = (EditText) findViewById(R.id.et_num);
        }

    /**
    * 1
    */
        private void One(){
            perf = new SharedpreUtil(this);
            //启动显示参数
            Map<String, String> map = new HashMap<String,String>();
            map=perf.put();
            OneBelowZero.setText(map.get("name"));
            One.setText(map.get("age"));
        }

        public void save(View view){
          String girl = OneBelowZero.getText().toString();
          int age = Integer.valueOf(One.getText().toString());
          perf.save(path, girl, age);
         Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_LONG).show();
        }
      }

    >3.接下来我们就 二生三了 sp怎么存list呢?没有方法啊?

    这就是sp的不好的地方了,做的话也可以,序列化呗,稍微麻烦点见代码:

    package com.example.cacheutil.sp;

    import java.io.ByteArrayInputStream;
    import java.io.ByteArrayOutputStream;
    import java.io.IOException;
    import java.io.ObjectInputStream;
    import java.io.ObjectOutputStream;
    import java.io.StreamCorruptedException;
    import java.util.List;

    import android.util.Base64;

    public class SPSceneListUtil {

      // 将list集合转换成字符串 SceneList to String
      public static String SceneList2String(List SceneList) throws IOException {
        // 实例化一个ByteArrayOutputStream对象,用来装载压缩后的字节文件。
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        // 然后将得到的字符数据装载到ObjectOutputStream
        ObjectOutputStream objectOutputStream = new ObjectOutputStream(
        byteArrayOutputStream);
        // writeObject 方法负责写入特定类的对象的状态,以便相应的 readObject 方法可以还原它
        objectOutputStream.writeObject(SceneList);
        // 最后,用Base64.encode将字节文件转换成Base64编码保存在String中
        String SceneListString = new String(Base64.encode(
        byteArrayOutputStream.toByteArray(), Base64.DEFAULT));
        // 关闭objectOutputStream
        objectOutputStream.close();
        return SceneListString;
      }

      // 将字符串转换成list集合 String to SceneList
      public static List String2SceneList(String SceneListString)
                  throws StreamCorruptedException, IOException,
                                ClassNotFoundException {
        byte[] mobileBytes = Base64.decode(SceneListString.getBytes(),
                                    Base64.DEFAULT);
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(
                                    mobileBytes);
        ObjectInputStream objectInputStream = new ObjectInputStream(
                                    byteArrayInputStream);
        List SceneList = (List) objectInputStream.readObject();
            objectInputStream.close();
            return SceneList;
        }

    }

    ==============================
    在activity中:
     


    public class MainActivity extends Activity {

      private EditText OneBelowZero;
      private EditText One;
      public static String path = "shared_file";
      public static String path2 = "shared_file2";
      private SharedpreUtil perf;
      private SharedPreferences sp;
      private Editor edit;

      @Override
      protected void onCreate(Bundle savedInstanceState) {
          super.onCreate(savedInstanceState);
          setContentView(R.layout.activity_main);

          OneBelowZero = (EditText) findViewById(R.id.et_str);
          One = (EditText) findViewById(R.id.et_num);
        }

    /**
    * 1 以下所有顺需都是 取 存 的顺序
    */
    private void One() {
    perf = new SharedpreUtil(this);
    // 启动显示参数
    Map<String, String> map = new HashMap<String, String>();
    map = perf.put();
    OneBelowZero.setText(map.get("name"));
    One.setText(map.get("age"));
    }

    public void save(View view) {
    String girl = OneBelowZero.getText().toString();
    int age = Integer.valueOf(One.getText().toString());
    perf.save(path, girl, age);
    Toast.makeText(MainActivity.this, "保存成功", Toast.LENGTH_LONG).show();
    }

    /**
    * 2
    */
        public List Two() {
          sp = getSharedPreferences(path2, MODE_PRIVATE);
          String liststr = sp.getString(path2, "");//
          List list=null;
          if (!TextUtils.isEmpty(liststr)) {
          try {
            list = SPSceneListUtil.String2SceneList(liststr);
          } catch (Exception e) {
              e.printStackTrace();
          }
          return list;
          }
      return null;
      }
      private String save2(List list) {
        sp = getSharedPreferences(path2, Context.MODE_PRIVATE);
        edit = sp.edit();
        String listStr = null;
        try {
        listStr = SPSceneListUtil.SceneList2String(list);
        // 存储
        edit.putString("mylistStr", listStr);
        edit.commit();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return listStr;
      }

    }

    有点麻烦啊,转化一下思路: 反正我的list集合是解析添加进去的,我直接获取服务器返回的json字符串不就好了吗?
    有道理:
    存:

    SharedPreferences sp = context.getSharedPreferences(path, Context.MODE_PRIVATE);
    Editor editor = sp.edit();
    editor.putString(key, mJsonArray.toString());//放你的数据
    editor.commit();

    取:

    List<map<string, string="">> datas = new ArrayList<map<string, string="">>();
        SharedPreferences sp = context.getSharedPreferences("finals", Context.MODE_PRIVATE);
        String result = sp.getString(key, "");
    这种做法也挺简单的,见这位仁兄:http://www.2cto.com/kf/201503/385503.html
    到此 SharedPreferences真的是用够了!!!
     
     
    =================================================
    ==================================================
    ==================================================
    ACache,轻量级:
     
    这个不详细说了
     
    Data
    获取全局传递参数的工具类绝对轻量级:

    import java.util.AbstractMap;
    import java.util.concurrent.ConcurrentHashMap;

    /**
    * 存取数据
    */
    public class Data {

    private static AbstractMap<String, Object> mData = new ConcurrentHashMap<String, Object>();

    private Data() {

    }

    public static void putData(String key,Object obj) {
    mData.put(key, obj);
    }

    public static Object getData(String key) {
    return mData.get(key);
    }
    }

    最后的最后:

    提供可增删改查的 缓存工具类:

    BestCacheUtil:

    package com.example.cacheutil;

    import java.io.File;
    import java.io.FileInputStream;
    import java.io.FileNotFoundException;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.OutputStream;
    import java.io.UnsupportedEncodingException;
    import java.net.URLDecoder;
    import java.net.URLEncoder;
    import java.util.HashMap;
    import java.util.Map;
    import java.util.Map.Entry;
    import java.util.Properties;
    import java.util.Set;

    import android.content.Context;

    /**
    * 主要用于存储简单key value键值对。提供增、删、改、查方法。 可自定义路径
    * @author Administrator
    */
    public class BestCacheUtil {
    private static Properties properties = new Properties();
    private static String filepath;

    private BestCacheUtil() {
    }

    //文件名
    public static BestCacheUtil get(Context ctx, String fileName) {
    return get(ctx.getCacheDir() + "/" + fileName);
    }
    /**
    * @param filePath
    * 文件绝对路径
    */
    public static BestCacheUtil get(String filePath) {
    createFile(filePath);
    filepath = filePath;
    try {
    properties.load(new FileInputStream(filepath));
    return new BestCacheUtil();
    } catch (FileNotFoundException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }
    return null;
    }
    /**
    * 没有就创建
    * @param fileName
    */
    private static void createFile(String fileName) {
    File file = new File(fileName);
    if (!file.exists()) {
    String path = file.getAbsolutePath();
    String[] sourceStrArray = path.split("/");
    String dirPath = "";
    for (int i = 0; i < sourceStrArray.length - 1; i++) {
    if (!sourceStrArray[i].equals("")) {
    dirPath += "/" + sourceStrArray[i];
    }
    }
    new File(dirPath).mkdirs();
    try {
    file.createNewFile();
    } catch (IOException e) {
    e.printStackTrace();
    }
    }

    }

    /**
    * 完全模仿ACache啊 嘿嘿
    * @param key
    * @return
    */
    public String getAsString(String key) {
    if (key == null) {
    return null;
    }
    Properties props = new Properties();
    try {
    props.load(new FileInputStream(filepath));
    String value = props.getProperty(key);
    value = URLDecoder.decode(value, "utf-8");
    return value;
    } catch (Exception e) {
    e.printStackTrace();
    return null;
    }
    }

    public int getAsInt(String key) {
    String str = getAsString(key);
    if (str == null)
    return -9999;
    return Integer.valueOf(str).intValue();
    }

    public boolean getAsBoolean(String key) {
    String str = getAsString(key);
    if (str == null)
    return false;
    if (str.equals("true"))
    return true;
    return false;
    }

    public long getAsLong(String key) {
    String str = getAsString(key);
    if (str == null)
    return -9999;
    return Long.valueOf(str).longValue();
    }

    public float getAsFloat(String key) {
    String str = getAsString(key);
    if (str == null)
    return -9999;
    return Float.valueOf(str).floatValue();
    }

    public double getAsDouble(String key) {
    String str = getAsString(key);
    if (str == null)
    return -9999;
    return Double.valueOf(str).doubleValue();
    }

    /**
    * 添加 变动的是:
    * @param keyname
    * @param keyvalue
    */
    public void put(String keyname, Object keyvalue) {
    // 处理中文乱码
    String value = keyvalue.toString();
    try {
    value = URLEncoder.encode(value, "utf-8");
    } catch (UnsupportedEncodingException e1) {
    e1.printStackTrace();
    }
    try {
    OutputStream fos = new FileOutputStream(filepath);
    properties.setProperty(keyname, value);
    properties.store(fos, null);
    } catch (IOException e) {
    }
    }

    /**
    * 更新
    * @param keyname
    * @param keyvalue
    */
    public void update(String keyname, String keyvalue) {
    try {
    properties.load(new FileInputStream(filepath));
    OutputStream fos = new FileOutputStream(filepath);
    properties.setProperty(keyname, keyvalue);
    properties.store(fos, null);
    } catch (IOException e) {
    }
    }

    /**
    * 根据key删除
    * @param key
    */
    public void delete(String key) {
    try {
    FileInputStream fis = new FileInputStream(filepath);
    properties.load(fis);
    Map map = new HashMap();
    Set keySet = properties.keySet();
    for (Object object : keySet) {
    String objectkey = (String) object;
    String value = (String) properties.get(objectkey);
    map.put(objectkey, value);
    }
    map.remove(key);
    properties.remove(key);
    Set<Map.Entry<String, String>> set = map.entrySet();
    for (Entry<String, String> entry : set) {
    properties.setProperty(entry.getKey(), entry.getValue());
    }
    FileOutputStream fos = new FileOutputStream(filepath);
    properties.store(fos, "delete key:" + key);
    fos.close();
    fis.close();
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
    }

     使用:::

        // 这里获取mCache对象。参数也可以为文件绝对路径,当然也可以直接传入Context和文件名。
        BestCacheUtil  mCache = BestCacheUtil.get("test.txt");
        // 增加
        mCache.put("key", "OneBelowZero");
        // 更新
        mCache.update("key", "帅");
        // 查找,这里提供多个getAs 方法。取数据找到相应的数据类型
        mCache.getAsString("key");
     
        // 删除
        mCache.delete("key");

    根据ACache改的哦!

    另外关于三级缓存:

    见:http://www.cnblogs.com/yizuochengchi2012/p/5034825.html

     欢迎大家加入群学习交流:Android&Go,Let's go! 521039620
     
    资源下载:http://download.csdn.net/detail/onebelowzero2012/9345713
     
    关于高的自动定位包明天再上传吧,至此,向所有师兄们致敬!
     
     
     
     
     
     
  • 相关阅读:
    SpringBoot
    SpringBoot
    MySQL
    Database
    Database
    MySQL
    Debug
    《mysql必知必会》学习_第18章
    C#中访问私有成员
    精彩语录收集
  • 原文地址:https://www.cnblogs.com/yizuochengchi2012/p/5037853.html
Copyright © 2020-2023  润新知