得到配置文件内容,其最大的问题就是文件路径的定位:java
经过ClassLoader去加载资源。参数须要从classpath的入口来算起。也就是说须要取全路径名称。ide
String path = 当前类名.class.getClassLoader().getResource("").toURI().getPath() ; //默认的是到src文件夹下spa
或者操作系统
String path = 当前类名.getClassLoader().getResourceAsStream("conf/key-conf.properties"); //src文件夹下的conf/key-conf.propertiescode
1、使用java.util.Properties类的load()方法 blog
InputStream in = lnew BufferedInputStream(new FileInputStream(name)); Properties p = new Properties(); p.load(in);
二、使用java.util.ResourceBundle类的getBundle()方法 资源
ResourceBundle这个类提供软件国际化的捷径 。使用这个类,要注意的一点是,这个properties文件的名字是有规范的:get
通常的命名规范是: 自定义名_语言代码_国别代码.properties, event
定义资源文件,放到src的根目录下面:(注意不在src的根目录下,路径分割符用的是 " . ")class
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"));