在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下,並交由系統統一管理 用此方法讀寫文件時,不能為文件指定具體路徑 |
|