您的位置:首页 > 移动开发 > Android开发

Android Properties 存储

2015-08-21 10:15 375 查看
1.初始化

private static void initProperties(){
File logFile = new File(Constants.PROGRESS_PROPERTIES);
props = new Properties();
if(!logFile.exists()){
//创建并初始化配置文件
FileUtils.createFolder(Constants.BASEPATH + "Config");// 先创建文件夹
RootUtil.execAsRoot("echo \"\" > " + Constants.PROGRESS_PROPERTIES, "chmod 666 " + Constants.PROGRESS_PROPERTIES);
persistent(-1, -1, -1, -1, "-1", "-1" , 0, 0, "-1", "-1", 0, 0, "-1", "-1", "-1", "-1", "-1", "-1");
}else{
loadProgress(props, Constants.PROGRESS_PROPERTIES);
}
}


2.存储

/**
* 持久化      * @param channel
* @param app
* @return
*/
public static boolean persistent(int channel, int app){
props.setProperty(KEY_CHANNEL, String.valueOf(channel));
props.setProperty(KEY_APP, String.valueOf(app));
FileOutputStream fos = null;
try{
fos = new FileOutputStream(Constants.PROGRESS_PROPERTIES);
props.store(fos, null);
return true;
}catch(Exception e){
return false;
}finally{
if(fos != null){
try
{
fos.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}


3.获取持久化值

/**
* 获取属性值
* @param key
* @return
*/
private static int getValue(String key){
try{
if(props == null){
initProperties();
}
return Integer.parseInt(props.getProperty(key));
}catch(Exception e){
e.printStackTrace();
}
return -1;
}

/**
* 获取属性值
* @param key
* @return
*/
private static String getValueForStr(String key){
try{
if(props == null){
initProperties();
}
return props.getProperty(key);
}catch(Exception e){
e.printStackTrace();
}
return "-1";
}


其中包含获取assets文件夹目录下的配置文件:

/**
* 获取配置文件中的value
* @param url 路径
* @param param 参数
* @param getFlag 访问标识  0:SD , 1 Assets
* @return
*/
public String getValue(String url, String param, int getFlag) {
String result = null;
switch(getFlag){
case 0:
result = getProperties(url).getProperty(param);
break;
case 1:
result = getPropertiesByAssets(url).getProperty(param);
break;
}

try {
if (fis != null) {
fis.close();
}
if(in != null){
in.close();
}
} catch (Exception e) {
e.printStackTrace();
}
return result == null ? "" : result;
}


4.当初始化好的文件,重新加载。

/**
* 加载属性
* @param props
*/
private static void loadProgress(Properties props, String file){
FileInputStream fis = null;
try{
fis = new FileInputStream(file);
props.load(fis);             if(props.get(KEY_CHANNEL) == null){
props.setProperty(KEY_CHANNEL, String.valueOf(-1));
}
if(props.get(KEY_APP) == null){
props.setProperty(KEY_APP, String.valueOf(-1));
}         }catch(Exception e){
e.printStackTrace();
}finally{
if(fis != null){
try
{
fis.close();
}
catch(Exception e){
e.printStackTrace();
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: