您的位置:首页 > 移动开发 > Android开发

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

2016-01-08 16:19 197 查看
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下,并交由系统统一管理

用此方法读写文件时,不能为文件指定具体路径
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: