废话不说,直接上代码。
读取.properties文件中的配置:
ide
- String strValue = "";
- Properties props = new Properties();
- try {
- props.load(context.openFileInput("config.properties"));
- strValue = props.getProperty (keyName);
- System.out.println(keyName + " "+strValue);
- }
- catch (FileNotFoundException e) {
- Log.e(LOG_TAG, "config.properties Not Found Exception",e);
- }
- catch (IOException e) {
- Log.e(LOG_TAG, "config.properties IO Exception",e);
- }
相信上面这段代码大部分朋友都能看懂,因此就不作过多的解释了。spa
向.properties文件中写入配置:get
- Properties props = new Properties();
- try {
- props.load(context.openFileInput("config.properties"));
- OutputStream out = context.openFileOutput("config.properties",Context.MODE_PRIVATE);
- Enumeration<?> e = props.propertyNames();
- if(e.hasMoreElements()){
- while (e.hasMoreElements()) {
- String s = (String) e.nextElement();
- if (!s.equals(keyName)) {
- props.setProperty(s, props.getProperty(s));
- }
- }
- }
- props.setProperty(keyName, keyValue);
- props.store(out, null);
- String value = props.getProperty(keyName);
- System.out.println(keyName + " "+value);
- }
- catch (FileNotFoundException e) {
- Log.e(LOG_TAG, "config.properties Not Found Exception",e);
- }
- catch (IOException e) {
- Log.e(LOG_TAG, "config.properties IO Exception",e);
- }
上面这段代码,跟读取的代码相比,多了一个if判断以及一个while循环。主要是由于Context.Mode形成的。由于个人工程涉及到多个配置信息。因此只能是先将全部的配置信息读取出来,而后在写入配置文件中。
Context.Mode的含义以下:
1.MODE_PRIVATE:为默认操做模式,表明该文件是私有数据,只能被应用自己访问,在该模式下,写入的内容会覆盖原文件的内容。
2.MODE_APPEND:表明该文件是私有数据,只能被应用自己访问,该模式会检查文件是否存在,存在就往文件追加内容,不然就建立新文件。
3.MODE_WORLD_READABLE:表示当前文件能够被其余应用读取。
4.MODE_WORLD_WRITEABLE:表示当前文件能够被其余应用写入。string
注:.properties文件放置的路径为/data/data/packagename/files
it