maven项目怎么读取properties文件

tjzero_sapce 2021-01-30 09:36:38
小弟有个练手的maven项目,文件结构如图,DBPoolConnection需要读取properties,路径总写不对,

static {
Properties properties = loadPropertiesFile(path);
try {
druidDataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties); //DruidDataSrouce工厂模式
} catch (Exception e) {
log.error("获取配置失败");
}
}

private static Properties loadPropertiesFile(String fullFile) {
String webRootPath = null;
if (null == fullFile || fullFile.equals("")){
throw new IllegalArgumentException("Properties file path can not be null" + fullFile);
}
webRootPath = DBPoolConnection.class.getClassLoader().getResource("").getPath();
webRootPath = new File(webRootPath).getParent();
InputStream inputStream = null;
Properties p =null;
try {
inputStream = new FileInputStream(new File(webRootPath + File.separator + fullFile));
p = new Properties();
p.load(inputStream);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (null != inputStream){
inputStream.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
return p;
}
...全文
479 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
tjzero_sapce 2021-01-30
  • 打赏
  • 举报
回复
我想改成相对路径读取properties,这样打成jar之后运行也方便
tjzero_sapce 2021-01-30
  • 打赏
  • 举报
回复
那我第二行的 path 应该怎么写呢?
外力古德 2021-01-30
  • 打赏
  • 举报
回复
DBPoolConnection.class.getClassLoader().getResource("/"+fullFile)

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧