黑马程序员之在android程序中使用配置文件properties

  • 格式:docx
  • 大小:16.57 KB
  • 文档页数:2

黑马程序员之------在android程序中使用配置文件properties
在android程序中使用配置文件来管理一些程序的配置信息其实非常简单
1.读写函数分别如下:
2.
3.//读取配置文件
4.public Properties loadConfig(Context context, String file) {
5.Properties properties = new Properties();
6.try {
7.FileInputStream s = new FileInputStream(file);
8.properties.load(s);
9.} catch (Exception e) {
10.e.printStackTrace();
11.return null;
12.}
13.return properties;
14.}
15.//保存配置文件
16.public boolean saveConfig(Context context, String file, Properties properties) {
17.try {
18.File fil=new File(file);
19.if(!fil.exists())
20.fil.createNewFile();
21.FileOutputStream s = new FileOutputStream(fil);
22.properties.store(s, "");
23.} catch (Exception e) {
24.e.printStackTrace();
25.return false;
26.}
27.return true;
28.}
复制代码
这两个函数与Android一点关系都没有嘛。

所以它们一样可以在其他标准的java程序中被使用
在Android中,比起用纯字符串读写并自行解析,或是用xml来保存配置,
Properties显得更简单和直观,因为自行解析需要大量代码,而xml的操作又远不及Properties方便
贴一段测试的代码
1.private Properties prop;
2.
3.public void TestProp(){
4.boolean b=false;
5.String s="";
6.int i=0;
7.prop=loadConfig(context,"/mnt/sdcard/config.properties");
8.if(prop==null){
9.//配置文件不存在的时候创建配置文件初始化配置信息
10.prop=new Properties();
11.prop.put("bool", "yes");
12.prop.put("string", "aaaaaaaaaaaaaaaa");
13.prop.put("int", "110");//也可以添加基本类型数据 get时就需要强制转换成封装类型
14.saveConfig(context,"/mnt/sdcard/config.properties",prop);
15.}
16.prop.put("bool", "no");//put方法可以直接修改配置信息,不会重复添加
17.b=(((String)prop.get("bool")).equals("yes"))?true:false;//get出来的都是Object对象如果是基本类型需要用到封
装类
18.s=(String)prop.get("string");
19.i=Integer.parseInt((String)prop.get("int"));
20.saveConfig(context,"/mnt/sdcard/config.properties",prop);
21.
22.}
复制代码
也可以用Context的openFileInput和openFileOutput方法来读写文件此时文件将被保存在/data/data/package_name/files下,。