1.初始化
1 private static void initProperties(){ 2 File logFile = new File(Constants.PROGRESS_PROPERTIES); 3 props = new Properties(); 4 if(!logFile.exists()){ 5 //创建并初始化配置文件 6 FileUtils.createFolder(Constants.BASEPATH + "Config");// 先创建文件夹 7 RootUtil.execAsRoot("echo \"\" > " + Constants.PROGRESS_PROPERTIES, "chmod 666 " + Constants.PROGRESS_PROPERTIES); 8 persistent(-1, -1, -1, -1, "-1", "-1" , 0, 0, "-1", "-1", 0, 0, "-1", "-1", "-1", "-1", "-1", "-1"); 9 }else{10 loadProgress(props, Constants.PROGRESS_PROPERTIES);11 }12 }
2.存储
1 /** 2 * 持久化 4 * @param channel 5 * @param app 6 * @return 7 */ 8 public static boolean persistent(int channel, int app){14 19 props.setProperty(KEY_CHANNEL, String.valueOf(channel));20 props.setProperty(KEY_APP, String.valueOf(app));36 37 FileOutputStream fos = null;38 try{39 fos = new FileOutputStream(Constants.PROGRESS_PROPERTIES);40 props.store(fos, null);41 return true;42 }catch(Exception e){43 return false;44 }finally{45 if(fos != null){46 try47 {48 fos.close();49 }50 catch(Exception e){51 e.printStackTrace();52 }53 }54 }55 }
3.获取持久化值
1 /** 2 * 获取属性值 3 * @param key 4 * @return 5 */ 6 private static int getValue(String key){ 7 try{ 8 if(props == null){ 9 initProperties();10 }11 return Integer.parseInt(props.getProperty(key));12 }catch(Exception e){13 e.printStackTrace();14 }15 return -1;16 }17 18 /**19 * 获取属性值20 * @param key21 * @return22 */23 private static String getValueForStr(String key){24 try{25 if(props == null){26 initProperties();27 }28 return props.getProperty(key);29 }catch(Exception e){30 e.printStackTrace();31 }32 return "-1";33 }
其中包含获取assets文件夹目录下的配置文件:
1 /** 2 * 获取配置文件中的value 3 * @param url 路径 4 * @param param 参数 5 * @param getFlag 访问标识 0:SD , 1 Assets 6 * @return 7 */ 8 public String getValue(String url, String param, int getFlag) { 9 String result = null;10 switch(getFlag){11 case 0:12 result = getProperties(url).getProperty(param);13 break;14 case 1:15 result = getPropertiesByAssets(url).getProperty(param);16 break;17 }18 19 try {20 if (fis != null) {21 fis.close();22 }23 if(in != null){24 in.close();25 }26 } catch (Exception e) {27 e.printStackTrace();28 }29 return result == null ? "" : result;30 }
4.当初始化好的文件,重新加载。
1 /** 2 * 加载属性 3 * @param props 4 */ 5 private static void loadProgress(Properties props, String file){ 6 FileInputStream fis = null; 7 try{ 8 fis = new FileInputStream(file); 9 props.load(fis);13 if(props.get(KEY_CHANNEL) == null){14 props.setProperty(KEY_CHANNEL, String.valueOf(-1));15 }16 if(props.get(KEY_APP) == null){17 props.setProperty(KEY_APP, String.valueOf(-1));18 }64 }catch(Exception e){65 e.printStackTrace();66 }finally{67 if(fis != null){68 try69 { 70 fis.close();71 }72 catch(Exception e){73 e.printStackTrace();74 }75 }76 }77 }