背景
我需要在配置文件中设置一些参数,然后在代码中获取数据使用。我的配置文件放在了src/main/resources文件夹下面了。
思路
主要是通过当前类加载器,通过加载resources资源文件为流,然后使用Properties类的load方法加载资源文件流即可,读取资源文件中的参数。
解决
Properties props = new Properties();
ClassLoader classLoader = getClass().getClassLoader();
InputStream stream = classLoader.getResourceAsStream("views.properties");
try {
props.load(stream);
props.getProperty("mykey", "myvalue");// 该方法即可使用数据
} catch (IOException e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
**Note:**注意关闭流操作。
参考: Java – Read a file from resources folder Reading Properties file