Android 讀寫配置文件properties

1、首先在源代碼根目錄(src下)下創建一個名爲global.properties的文件(也可以在其他目錄下)。或者在assets文件夾下創建一個名爲global.properties的文件。

2、打開global.properties文件,在該文件中添加下列代碼

#後臺接口url
url=http://121.15.209.220
#端口號
port=8080

說明:上面代碼中,#爲配置文件中的註釋,而在配置文件中,可以使用<br>等進行格式處理,在配置文件中,如果某個屬性過長,一行不能輸入完全是,可以通過 通知系統,下一行同樣爲該屬性的值。

3、創建一個工具類

/**
 * 配置文件讀取
 */
public class PropertiesUtils {

    //1、配置文件的位置在assets資源目錄下
    private final static String m_strPath = "/assets/global.properties";
    //2、配置文件的位置在源代碼根目錄(src下)
    //private final static String m_strPath = "/global.properties";

    public static Properties getProperties(Context c){
        Properties props = new Properties();
        try {
            //方法一:通過activity中的context獲取setting.properties的FileInputStream
            //注意這地方的參數appConfig在eclipse中應該是appConfig.properties纔對,但在studio中不用寫後綴
            //InputStream in = c.getAssets().open("appConfig.properties");
            //InputStream in = c.getAssets().open("appConfig");
            //方法二:通過class獲取setting.properties的FileInputStream
            InputStream in = PropertiesUtils.class.getResourceAsStream(m_strPath);
            props.load(in);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return props;
    }

    /**
     * 使用樣例
     */
    private void example(){
        //String url = PropertiesUtils.getProperties(getApplicationContext()).getProperty("url");
        String url = PropertiesUtils.getProperties(null).getProperty("url");
    }

}

4.在需要使用配置文件中配置的屬性值時,直接調用上述方法即可,如下所示。

 String url = PropertiesUtils.getProperties(null).getProperty("url");

完!!!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章