1. 程式人生 > >在android程式中使用配置檔案properties

在android程式中使用配置檔案properties

專案需求是:程式啟動時讀取配置檔案,啟動後在設定裡面可以修改配置檔案並儲存到指定的配置檔案裡面。而在android程式中使用配置檔案來管理一些程式的配置資訊其實非常簡單

在這裡我們主要就是用到Properties這個類

直接給函式給大家 這個都挺好理解的

	/**
	 * 讀取配置檔案
	 * <p>
	 * Title: loadConfig
	 * <p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @param context
	 * @param file
	 * @return
	 */
	public static 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;
	}

	/**
	 * 儲存配置檔案
	 * <p>
	 * Title: saveConfig
	 * <p>
	 * <p>
	 * Description:
	 * </p>
	 * 
	 * @param context
	 * @param file
	 * @param properties
	 * @return
	 */
	public static 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);
	}
另外記得在相應的位置新增許可權:
 <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
    <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>

也可以用Context的openFileInput和openFileOutput方法來讀寫檔案
此時檔案將被儲存在 /data/data/package_name/files下,並交由系統統一管理

用此方法讀寫檔案時,不能為檔案指定具體路徑

本文轉載自http://www.cnblogs.com/SummerRain/p/3266584.html