Android保存键值,不用占用内存的sharedPreference,而是Properties本地文件

SharedPreference放在data/data/包名/下面。

是占用内存得,如果保存大量的数据,需要放到sdcard下去,所以SharedPreferences不方便,直接用Properties类的方式比较好。

可以把文件当作字符串传入,能访问获取正确值就好!```


package com.nil.cache;

import java.io.File;

import java.io.FileInputStream;

import java.io.FileNotFoundException;

import java.io.FileOutputStream;

import java.io.IOException;

import java.io.InputStream;

import java.util.Properties;

public class PropertiesConfig extends Properties {

String propertyPath="";

private PropertiesConfig(String path) {

propertyPath=path;

};

public static PropertiesConfig getInstance(String path) {

{

File file = new File(path);

if (file.exists()) {

try {

file.createNewFile();

} catch (IOException e) {

e.printStackTrace();

}

}

PropertiesConfig pro = new PropertiesConfig(path);

try {

InputStream is = new FileInputStream(file);

pro.load(is);

is.close();

} catch (Exception e) {

e.printStackTrace();

}

return pro;

}

}

@Override

public Object setProperty(String key, String value) {

super.setProperty(key, value);

try {

this.store(new FileOutputStream(this.propertyPath),

"utf-8");

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return value;

}

public Object put(String key, String value) {

super.put(key, value);

try {

this.store(new FileOutputStream(this.propertyPath),

"utf-8");

} catch (FileNotFoundException e) {

e.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}

return value;

}

}

嘿嘿!怎么用呢?

大概如下调用即可:


[java]

PropertiesConfig.getInstance("/sdcard/client_config.xml").setProperty("187", "name");

PropertiesConfig.getInstance("/sdcard/client_config.xml").get("187");

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 面试题总结 通用 安卓学习途径, 寻找资料学习的博客网站 AndroidStudio使用, 插件使用 安卓和苹果的...
    JingBeibei阅读 1,721评论 2 21
  • 在 Activity 获取字符串资源: this.getString(R.string.hello) 从 Cont...
    allencaicai阅读 973评论 0 1
  • permissionn.允许;批准,正式认可,认可user permission 使用权限permission D...
    lengol阅读 1,051评论 0 51
  • 如果真的爱,不应该是当下所有,只为在一起,而不是一等二等再三等吗? 如果真的爱,还会是那种“我从你那里得到的,我可...
    monica文静阅读 228评论 0 0
  • 简评:清晰的资源目录结构能节省你的时间,时间就是金钱。 相信每一位 Android 开发者对于这样的项目目录都已经...
    极小光阅读 1,685评论 0 6