1. 程式人生 > >在Android Studio中讀取properties檔案

在Android Studio中讀取properties檔案

在開發過程中,如果有一些引數變數是需要經常改動的,就可以放在properties的配置檔案中,而不用寫死在程式碼中。如果想要修改這些引數,只需要在配置檔案中修改即可。以Android Studio為例:

1.首先在工程中建立assets資料夾,在資料夾中建立properties檔案。

首先,右鍵點選工程的app,選擇New—>Folder—>Assets Folder,成功新建Assets資料夾。然後,右鍵點選新建的assets資料夾—>New—>File—>輸入檔案的名字為xxx.prop(這裡命名為publish.properties)

2.在prop檔案中新增需要靈活控制的引數,以鍵值對的形式新增,如:

baseUrl=www.baudu.com

3.加入讀取引數的程式碼(實現一個方法):

public class PropertiesUtil {
    public static String load(String key) {
        String value = null;
        Properties properties = new Properties();
        try {
            properties.load(BaseApplication.getInstance().getAssets().open("publish.properties"));
            value = properties.getProperty(key);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }
}

在這裡需要傳入獲取引數的key值以及Context值,即可獲取返回的value值。如果想要修改,也只需要在prop檔案中修改即可,不需要修改程式碼。

4.如果想要獲取,假設展示在Activity中:

PropertiesUtil.load(ConstantValue.Config.BaseUrl)