适用场景:代码当中需要读取配置文件进行操作时,可以用Properties类进行读写方便快捷
1、获取配置文件中的值放入到Properties中
private static synchronized Properties get() { FileInputStream fis = null; Properties props = new Properties(); try { Log.d(TAG, "get()--getPath():" + getAdbConfigPath()); File file = null; file = new File(getAdbConfigPath()); if (!file.exists()) { try { Log.d(TAG, "get()--getPath():----createNewFile()"); file.createNewFile(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } Log.d(TAG, "get()--file:" + file.length()); fis = new FileInputStream(file); props.load(fis); } catch (Exception e) { e.printStackTrace(); } finally { try { fis.close(); } catch (IOException e) { e.printStackTrace(); } } return props; }
2、获取配置文件并对其进行更新
public static synchronized void setProps(Properties p) { FileOutputStream fos = null; try { File file = null; file = new File(getAdbConfigPath()); Log.d(TAG, "Properties---setProps(String configName, Properties p)--写文件路径:file:" + file.length()); fos = new FileOutputStream(file); p.store(fos, null); } catch (Exception e) { Log.d(TAG, "Properties---setProps(String configName, Properties p)---写文件异常抛出"); e.printStackTrace(); } finally { Log.d(TAG, "Properties---setProps(String configName, Properties p)---写文件关闭"); try { fos.flush(); fos.close(); } catch (IOException e) { e.printStackTrace(); } } }
3、编写对外提供读取值方法,根据传进来的key值进行读取Value值
public String get(String key) { Properties props = get(); String propsValue = null; if (props != null) { propsValue = props.getProperty(key); Log.d(TAG, "get(String key)--propsValue:" + propsValue); } return propsValue; }
4、编写对外提供写入Value值的方法,传入的参数为键值对。
public void set(String key, String value) { Log.d(TAG, "set(String key, String value)--- key:" + key + " value:" + value); Properties props = get(); props.setProperty(key, value); setProps(props); }
5、编写对外提供的删除方法,传入参数为key值
public void remove(String configName, String... key) { Properties props = get(); for (String k : key) { props.remove(k); } setProps(props); }