网上的办法都不靠谱,没说到点上。
在发布war包时,weblogic会自动把classes下面的文件编译成一个_wl_cls_gen.jar 文件,放在WEB-INF/lib下面。
这时,我们不能使用先获取文件路径,再通过new File(filePath)的方式获取文件。因为获取到的路径是以zip://开头的。
例如:
String path = this.class.getClassLoader().getResource("config/config.properties").getPath();
File file = new File(path);
直接获取文件流就可以了。
ClassLoader classloader =Thread.currentThread().getContextClassLoader();
InputStream is = classloader.getResourceAsStream("config/config.properties");
说明:config/config.properties:config.properties是在_wl_cls_gen.jar的config目录下。
以下是源码:
//获取ClassLoader
ClassLoader classloader =Thread.currentThread().getContextClassLoader();
String aae100="";
InputStream is = null;
try {
is = classloader.getResourceAsStream("config/config.properties");
Properties prop = new Properties();
prop.load(is);
aae100 = prop.getProperty("aae100");
}catch (Exception e) {
e.printStackTrace();
}finally {
if (is != null) {
try {
is.close();
}catch (Exception e) {
e.printStackTrace();
}
}
}