android 如何創建配置文件和讀配置文件


因為一些配置信息,多處用到的。且以后可能變更的,我想寫個.prorperties配置文件給管理起來。在studio中新建一個Assets文件——>新建一個file文件類型為properties文件,該文件可以與res,java同級
這里寫圖片描述

這里寫圖片描述

這里寫圖片描述

這里寫圖片描述

這里寫圖片描述

我把配置文件放在了assets文件夾下

appConfig:

serverUrl=http://192.168.110:8088/ap

操作的工具類:
ProperTies :

public class ProperTies {

    public static Properties getProperties(Context c){
        Properties urlProps;
        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 = PropertiesUtill.class.getResourceAsStream("/assets/ setting.properties "));
            props.load(in);
        } catch (Exception e1) {
            // TODO Auto-generated catch block
            e1.printStackTrace();
        }

        urlProps = props;
        return urlProps;
    }
}

使用:

Properties proper = ProperTies.getProperties(getApplicationContext());
                String serviceUrl = proper.getProperty("serverUrl");
                Log.i("TAG", "serviceUrl=" + serviceUrl);

測試結果為:

01-25 07:51:50.743 13019-13019/? I/TAG: serviceUrl=http://192.168.110:8088/ap


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM