当前位置: 代码迷 >> Android >> Android停用Properties保存程序配置
  详细解决方案

Android停用Properties保存程序配置

热度:88   发布时间:2016-05-01 19:09:08.0
Android下用Properties保存程序配置

读写函数分别如下:

?

import java.io.FileInputStream;import java.io.FileOutputStream;import java.util.Properties;public Properties loadConfig(Context context, String file) {Properties properties = new Properties();try {FileInputStream s = new FileInputStream(file);properties.load(s);} catch (Exception e) {e.printStackTrace();}return properties;}public void saveConfig(Context context, String file, Properties properties) {try {FileOutputStream s = new FileOutputStream(file, false);properties.store(s, "");} catch (Exception e){e.printStackTrace();}} 

?
orz,是不是发现什么了?对了,这两个函数与Android一点关系都没有嘛。。
所以它们一样可以在其他标准的java程序中被使用
在Android中,比起用纯字符串读写并自行解析,或是用xml来保存配置,
Properties显得更简单和直观,因为自行解析需要大量代码,而xml的操作又远不及Properties方便

使用方法如下:
写入配置:

view plaincopy to clipboardprint?Properties prop = new Properties();prop.put("prop1", "abc");prop.put("prop2", 1);prop.put("prop3", 3.14);saveConfig(this, "/sdcard/config.dat", prop); 

?

?

读取配置:

view plaincopy to clipboardprint?Properties prop = loadConfig(this, "/sdcard/config.dat");String prop1 = prop.get("prop1"); 

注:也可以用Context的openFileInput和openFileOutput方法来读写文件
此时文件将被保存在 /data/data/package_name/files下,并交由系统统一管理
用此方法读写文件时,不能为文件指定具体路径。

?

文件读取和保持的四种权限:

权限:android有四种权限

???? 1.Context.MODE_PRIVATE

???????? 私有属性,只有自己可以访问,并且第二次写入的内容会覆盖第一次写入的内容

???? 2.Context.MODE_APPEND

??????? 私有属性,只有自己可以访问,第二次写入的内容会追加到第一次写入的内容的后面

??? 3.Context.MODE_WORLD_WRITEABLE

?????? 公有属性,其它项目都可以写入,不过第二次写入的内容会覆盖第一次写入的内容

?? 4.Context.MODE_WORLD_READABLE

????? 公有属性,其它项目都可以读取

权限是可以相加的,比如

???????? 现在我想要一个其它项目可以读取,并且也可以写入,还可以追加

????????? Context.MODE_WORLD_READABLE+Context.MODE_WORLD_WRITEABLE+Context.MODE_APPEND

?

?

void load()     {        Properties properties=new Properties();        try {            FileInputStream stream =this.openFileInput("music.cfg");            properties.load(stream);        } catch (FileNotFoundException e) {            // TODO: handle exception            return;        } catch (IOException e) {            // TODO Auto-generated catch block            return;        }        isplay=Boolean.valueOf(properties.get("isplay").toString());    } boolean save()    {        Properties properties =new Properties();         properties.put("isplay", String.valueOf(isplay));        try {            FileOutputStream stream=this.openFileOutput("music.cfg", Context.MODE_WORLD_WRITEABLE);            properties.store(stream, "");        } catch (FileNotFoundException e) {            // TODO: handle exception            return false;        }catch (IOException e) {            // TODO: handle exception            return false;        }        return true;            }

?

?

本文来自CSDN博客,转载请标明出处:http://blog.csdn.net/ameyume/archive/2010/11/26/6037760.aspx

  相关解决方案