记录工作中常用方法,方便以后使用
InputStream inputStream = MyClass.class.getClassLoader().getResourceAsStream("config.properties"); //还有另一种方法
Properties p = new Properties();
try {
p.load(inputStream);
} catch (IOException e) {
logger.error("配置文件config.properties载入出错", e);
System.exit(-1); //文件不存在
}
if((config = p.getProperty(Config_Name)) == null){
logger.error("配置文件中 {} 字段不存在", Config_Name);
System.exit(-1);
}
以下2个方法效果一样
PropertisUtil.class.getResourceAsStream("/config.properties");
PropertisUtil.class.getClassLoader().getResourceAsStream("config.properties");
以他方法参照
本文分享了工作中常用的方法记录与配置文件加载的多种技巧,包括使用 ClassLoader 和 Resource API 加载 properties 文件,并提供了错误处理机制。通过实例演示了如何在遇到配置文件不存在或特定字段缺失时进行优雅的错误反馈。
1965

被折叠的 条评论
为什么被折叠?



