Javaweb读取自定义配置文件

Java中经常出现自定义的 properties 配置文件,可以简化更换参数时的复杂度

第一种方式(可用):
ResourceBundle:这个类主要用来解决国际化和本地化问题。
说的简单点,这个类的作用就是读取资源属性文件(properties),然后根据.properties文件的名称信息(本地化信息),匹配当前系统的国别语言信息(也可以程序指定),然后获取相应的properties文件的内容。
使用这个类,properties需要遵循一定的命名规范,一般的命名规范是: 自定义名语言代码国别代码.properties,如果是默认的,直接写为:自定义名.properties。

ResourceBundle bundle = ResourceBundle.getBundle("conf");
String name = bundle.getString("rest.enterprise.host");

Javaweb读取自定义配置文件

第二种方式(可用):
Properties类继承自Hashtable类并且实现了Map接口,也是使用一种键值对的形式来保存属性集。不过Properties有特殊的地方,就是它的键和值都是字符串类型。

Properties p = new Properties();
InputStream in = LoadProperties.class.getClassLoader().getResourceAsStream("conf.properties");
p.load(in);
String name = p.getProperty("rest.enterprise.host");
System.err.println("测试3:"+name3);

第三种方式 :
通过类加载器 加载配置文件

Properties p = new Properties();
InputStream in = LoadProperties.class.getClassLoader().getResourceAsStream("jdbc.properties");
p.load(in);
String name = p.getProperty("className");
System.out.println(name);