因为一些配置信息,多处用到的。且以后可能变更的,我想写个.prorperties配置文件给管理起来。在studio中新建一个 Assets文件——>新建一个file文件类型为properties文件,该文件可以与res,java同级
创建物理 android_assets 目录及 appConfig 文件




在 appConfig 文件中输入配置信息
serverUrl=http://www.xxx.com/
使用 Properties 来解析配置信息
创建 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://www.xxx.com/
转载请注明:隨習筆記 » android 如何创建配置文件和读配置