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

android程序中使用配置文件来管理一些程序的配置信息其实非常简单

在这里我们主要就是用到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 null;
}
return properties;
}
//保存配置文件
public boolean saveConfig(Context context, String file, Properties properties) {
try {
File fil=new File(file);
if(!fil.exists())
fil.createNewFile();
FileOutputStream s = new FileOutputStream(fil);
properties.store(s, "");
} catch (Exception e) {
e.printStackTrace();
return false;
}
return true;
}


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

贴一段测试的代码

private Properties prop;
public void TestProp(){
boolean b=false;
String s="";
int i=0;
prop=loadConfig(context,"/mnt/sdcard/config.properties");
if(prop==null){
//配置文件不存在的时候创建配置文件 初始化配置信息
prop=new Properties();
prop.put("bool", "yes");
prop.put("string", "aaaaaaaaaaaaaaaa");
prop.put("int", "110");//也可以添加基本类型数据 get时就需要强制转换成封装类型
saveConfig(context,"/mnt/sdcard/config.properties",prop);
}
prop.put("bool", "no");//put方法可以直接修改配置信息,不会重复添加
b=(((String)prop.get("bool")).equals("yes"))?true:false;//get出来的都是Object对象 如果是基本类型 需要用到封装类
s=(String)prop.get("string");
i=Integer.parseInt((String)prop.get("int"));
saveConfig(context,"/mnt/sdcard/config.properties",prop);
}


复制代码
也可以用Context的openFileInput和openFileOutput方法来读写文件
此时文件将被保存在 /data/data/package_name/files下,并交由系统统一管理
用此方法读写文件时,不能为文件指定具体路径
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值