获得配置文件内容,其最大的问题就是文件路径的定位:
通过ClassLoader去加载资源。参数需要从classpath的入口来算起。也就是说需要取全路径名称。
String path = 当前类名.class.getClassLoader().getResource("").toURI().getPath() ; //默认的是到src文件夹下
或者
String path = 当前类名.getClassLoader().getResourceAsStream("conf/key-conf.properties"); //src文件夹下的conf/key-conf.properties
1、使用java.util.Properties类的load()方法
InputStream in = lnew BufferedInputStream(new FileInputStream(name)); Properties p = new Properties(); p.load(in);
2、使用java.util.ResourceBundle类的getBundle()方法
ResourceBundle这个类提供软件国际化的捷径 。使用这个类,要注意的一点是,这个properties文件的名字是有规范的:
一般的命名规范是: 自定义名_语言代码_国别代码.properties,
如果是默认的,直接写为:
自定义名.properties
比如:
myres_en_US.properties
myres_zh_CN.properties
myres_zh_CN.properties
myres.properties
当在中文操作系统下,如果myres_zh_CN.properties、myres.properties两个文件都存在,则优先会使用myres_zh_CN.properties,当myres_zh_CN.properties不存在时候,会使用默认的myres.properties。
定义资源文件,放到src的根目录下面:(注意不在src的根目录下,路径分割符用的是 " . ")
myres.properties
aaa=good
bbb=thanks
bbb=thanks
myres_en_US.properties
aaa=good
bbb=thanks
bbb=thanks
myres_zh_CN.properties
aaa=\u597d
bbb=\u591a\u8c22
bbb=\u591a\u8c22
Locale locale1 = new Locale("zh", "CN"); ResourceBundle resb1 = ResourceBundle.getBundle("myres", locale1); System.out.println(resb1.getString("aaa")); ResourceBundle resb2 = ResourceBundle.getBundle("myres", Locale.getDefault()); System.out.println(resb1.getString("aaa")); Locale locale3 = new Locale("en", "US"); ResourceBundle resb3 = ResourceBundle.getBundle("myres", locale3); System.out.println(resb3.getString("aaa"));