SummerRain

软件开发/信息安全
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

【转】在android程序中使用配置文件properties

Posted on 2013-08-18 21:46  SummerRain  阅读(18216)  评论(0编辑  收藏  举报
在android程序中使用配置文件来管理一些程序的配置信息其实非常简单

在这里我们主要就是用到Properties这个类
直接给函数给大家 这个都挺好理解的
  1. 读写函数分别如下:
  2. //读取配置文件 
  3. public Properties loadConfig(Context context, String file) {
  4. Properties properties = new Properties();
  5. try {
  6. FileInputStream s = new FileInputStream(file);
  7. properties.load(s);
  8. } catch (Exception e) {
  9. e.printStackTrace();
  10. return null;
  11. }
  12. return properties;
  13. }
  14. //保存配置文件
  15. public boolean saveConfig(Context context, String file, Properties properties) {
  16. try {
  17. File fil=new File(file);
  18. if(!fil.exists())
  19. fil.createNewFile();
  20. FileOutputStream s = new FileOutputStream(fil);
  21. properties.store(s, "");
  22. } catch (Exception e) {
  23. e.printStackTrace();
  24. return false;
  25. }
  26. return true;
  27. }
复制代码
这两个函数与Android一点关系都没有嘛。。
所以它们一样可以在其他标准的java程序中被使用
在Android中,比起用纯字符串读写并自行解析,或是用xml来保存配置,
Properties显得更简单和直观,因为自行解析需要大量代码,而xml的操作又远不及Properties方便

贴一段测试的代码
  1. private Properties prop;
  2. public void TestProp(){
  3. boolean b=false;
  4. String s="";
  5. int i=0;
  6. prop=loadConfig(context,"/mnt/sdcard/config.properties");
  7. if(prop==null){
  8. //配置文件不存在的时候创建配置文件 初始化配置信息
  9. prop=new Properties();
  10. prop.put("bool", "yes");
  11. prop.put("string", "aaaaaaaaaaaaaaaa");
  12. prop.put("int", "110");//也可以添加基本类型数据 get时就需要强制转换成封装类型
  13. saveConfig(context,"/mnt/sdcard/config.properties",prop);
  14. }
  15. prop.put("bool", "no");//put方法可以直接修改配置信息,不会重复添加
  16. b=(((String)prop.get("bool")).equals("yes"))?true:false;//get出来的都是Object对象 如果是基本类型 需要用到封装类
  17. s=(String)prop.get("string");
  18. i=Integer.parseInt((String)prop.get("int"));
  19. saveConfig(context,"/mnt/sdcard/config.properties",prop);
  20. }
复制代码
也可以用Context的openFileInput和openFileOutput方法来读写文件
此时文件将被保存在 /data/data/package_name/files下,并交由系统统一管理
用此方法读写文件时,不能为文件指定具体路径