开发中有很多配置需要在配置文件中设置,这样读取也方便,修改也方便。
下面就来说一说在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";