java的Properties可以操作一个键值对类型数据保存的文件,同样可以在android进行保存数据。
可以作为工具类保存数据
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;
import android.content.Context;
import android.content.res.AssetManager;
public class PropertiesConfig extends Properties {
public static final String configPath = "config" + File.separator
+ "client_config.properties";
public static final String KEY_user_valid_code = "KEY_user_valid_code";
private static Context mContext;
private PropertiesConfig() {
};
private static PropertiesConfig mPro;
public static PropertiesConfig getInstance(Context mContext) {
if (PropertiesConfig.mContext == null || mPro == null) {
PropertiesConfig.mContext = mContext;
try {
//当且仅当不存在具有此抽象路径名指定名称的文件时创建一个新的空文件
File file=new File(configPath);
file.mkdirs();
file.createNewFile();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
PropertiesConfig pro = new PropertiesConfig();
//android的AssetManager类管理Asset文件夹下的资源
AssetManager am = mContext.getAssets();
try {
InputStream is = am.open(configPath);
pro.load(is);
is.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mPro = pro;
return pro;
}
return mPro;
}
@Override
public Object setProperty(String key, String value) {
super.setProperty(key, value);
try {
//保存键值对
this.store(new FileOutputStream(PropertiesConfig.configPath),
"utf-8");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return value;
}
public Object put(String key, String value) {
super.put(key, value);
try {
//保存键值对
this.store(new FileOutputStream(PropertiesConfig.configPath),
"utf-8");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return value; }
}