Java 读取jar内包资源文件和读取jar包外资源文件
程序员文章站
2022-03-02 17:15:19
...
Java 读取jar包内资源文件:
# 读取jar 包内资源文件application.properties
InputStream appPropertiesInputStream = ApplicationPropertiesHolder.class
.getClassLoader().getResourceAsStream("application.properties");
if (appPropertiesInputStream != null) {
try {
Properties appProperties = new Properties();
appProperties.load(appPropertiesInputStream);
if (logger.isDebugEnabled()) {
logger.debug("application.properties:");
for (Entry<Object, Object> entry : appProperties.entrySet()) {
logger.debug("*" + entry.getKey() + "=" + entry.getValue());
}
}
for (Entry<Object, Object> entry : appProperties.entrySet()) {
defaultProperties.put(entry.getKey(), entry.getValue());
}
} catch (IOException e) {
logger.error("Load application.properties error", e);
} finally {
if (appPropertiesInputStream != null) {
try {
appPropertiesInputStream.close();
appPropertiesInputStream = null;
} catch (IOException e) {
logger.error("InputStream Colse Error:", e);
}
}
}
}
Java 读取jar包外资源文件:
# 读取jar 同级目录的config/application.properties 文件
String dir =new File(ApplicationPropertiesHolder.class.getProtectionDomain().getCodeSource().getLocation().getPath()).getParent();
InputStream appPropertiesInputStream = new FileInputStream(new File(dir+File.separator+"config/application.properties"));
if (appPropertiesInputStream != null) {
try {
Properties appProperties = new Properties();
appProperties.load(appPropertiesInputStream);
if (logger.isDebugEnabled()) {
logger.debug("application.properties:");
for (Entry<Object, Object> entry : appProperties.entrySet()) {
logger.debug("*" + entry.getKey() + "=" + entry.getValue());
}
}
for (Entry<Object, Object> entry : appProperties.entrySet()) {
defaultProperties.put(entry.getKey(), entry.getValue());
}
} catch (IOException e) {
logger.error("Load application.properties error", e);
} finally {
if (appPropertiesInputStream != null) {
try {
appPropertiesInputStream.close();
appPropertiesInputStream = null;
} catch (IOException e) {
logger.error("InputStream Colse Error:", e);
}
}
}
}
上一篇: Teradata演绎大数据价值