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");

你可能感兴趣的:(Android保存键值,不用占用内存的sharedPreference,而是Properties本地文件)