Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 如何讀取 assets 中的 properties 設定檔

編輯:關於 Android 程式設計

專案裡總有一些「到處都會用到、以後又可能會改」的參數,例如伺服器位址。寫死在程式碼裡每次改都要重新編譯,實在麻煩。這時候把它抽到一個 .properties 檔裡統一管理,是成本最低的做法。

第一步:建立設定檔

把檔案放在 assets 目錄下,命名為 appConfig.properties:

serverUrl=https://192.168.1.155/ap

放在 assets 的好處是它不會被編譯進資源 ID,改內容不必動程式碼,也不必像 res/raw 那樣受資源系統約束。

第二步:寫一個讀取工具類

package cn.com.smartcost.offer.util;

import java.io.InputStream;
import java.util.Properties;
import android.content.Context;

/**
 * 讀取 properties 設定檔
 */
public class MyProperUtil {

    private static Properties urlProps;

    public static Properties getProperties(Context c) {
        Properties props = new Properties();
        try {
            // 方法一:透過 Context 取得 assets 中的檔案
            InputStream in = c.getAssets().open("appConfig.properties");
            // 方法二:透過 Class 取得
            // InputStream in = MyProperUtil.class.getResourceAsStream("/assets/appConfig.properties");
            props.load(in);
            in.close();
        } catch (Exception e1) {
            e1.printStackTrace();
        }
        urlProps = props;
        return urlProps;
    }
}

兩種寫法都可以,實際差異在於取得 InputStream 的路徑。用 Context 取 assets 直覺好懂;用 ClassLoader 取則在沒有 Context 的場合(例如純工具類)比較方便。

第三步:在需要的地方使用

Properties properties = MyProperUtil.getProperties(getApplicationContext());
String url = properties.getProperty("serverUrl");
Log.i("URL", url);

幾個實務上的建議

原始範例把 System.out.println 留在工具類裡,正式環境建議移除或改用 Log,避免無意義的輸出。另外,既然設定檔通常全程唯讀,可以在應用啟動時讀取一次並快取在單例中,不必每次取值都重新開檔。若參數屬於「正式環境不可竄改」的性質(例如 API 端點),也別忘了 assets 是使用者可讀的,敏感資訊應該放到服務端而非打包進 APK。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved