Android 笔记:读取配置文件config.properties

开发中有很多配置需要在配置文件中设置,这样读取也方便,修改也方便。

下面就来说一说在Android中怎么读取配置文件。

配置文件存放的位置是在/src/main/assets下,这个文件可以手动建也可以系统自己建,推荐大家手动建。

 

读取配置文件:

        

/**
 * @param c
 * @param s
 * @return 读取配置文件 config.properties
 */
public static String getPropertiesURL(Context c, String s) {
    String url = null;
    Properties properties = new Properties();
    try {
        properties.load(c.getAssets().open("config.properties"));
        url = properties.getProperty(s);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return url;

}

 

我的配置文件中放的是ip和端口,所以在onCreate方法中获取:

 

int port = Integer.parseInt(MainActivity.getPropertiesURL(this,"sentport"));
String ip = MainActivity.getPropertiesURL(this,"ip");
这样就完成了获取配置文件中值了。

 

把配置文件放在/massets文件夹下

config:    serverUrl=http://192.168.3.108/

操作的工具类:
ProperUtil :

/**
 * @author Evloution_
 * @date 2018/9/29
 * @explain 读取config配置文件工具类
 * 方法一:通过activity中的context攻取setting.properties的FileInputStream
 * 注意这地方的参数appConfig在eclipse中应该是appConfig.properties才对,但在studio中不用写后缀
 * InputStream in = c.getAssets().open("appConfig.properties");
 * 方法二:通过class获取setting.properties的FileInputStream
 * InputStream in = PropertiesUtill.class.getResourceAsStream("/assets/  setting.properties "));
 */
public class ProperUtil {

    public static Properties getPropertiesURL(Context c) {
        Properties urlProps;
        Properties properties = new Properties();
        try {
            properties.load(c.getAssets().open("config"));
        } catch (Exception e) {
            e.printStackTrace();
        }
        urlProps = properties;
        return urlProps;
    }
}

 

使用:

Properties proper = ProperUtil.getPropertiesURL(getApplicationContext());
String serviceUrl = proper.getProperty("serverUrl");
// 访问路径
String path = serviceUrl + "express/upload";

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值