如何从jar中读取类如XML的配置文件呢?而且要兼容读取classPath下的配置文件,且读取顺序要优先于jar包。
从classPath下读取大家都知道,通过class.getResource()就能获取class的绝对路径,读取非常轻松。而从jar中读取则需要支持的API,楼主翻阅了网上的资料,有URL、JarFile等。但这意味着方法里必须先读取classPath下文件,如没有则再读取jar中文件,这就显得很不优雅。
后来找到了一种优雅的API:ResourcePatternResolver
翻查了下它的源码,不仅支持优先从classPath下读取文件,也支持jar中读文件,而且还支持从war包中读取文件,简直太方便了。以下是楼主二次封装的工具类,读取文件后返回Document对象,这个对象默认是JDOM,当然也可以改为W3CDOM(改用SAXBuilder的方法解析下文件就可以了)。
//filePath = net/SIS/TEST.xml
public static org.w3c.dom.Document configFile2dom(String filePath) {
ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
try {
//1.文件存在否?2.文件后缀名匹配否?
Resource[] arr = resolver.getResources("classpath:"+filePath);
if(arr.length > 0) {
if(arr[0].getFilename().toLowerCase().endsWith(".xml")) {
DocumentBuilder documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
return documentBuilder.parse(arr[0].getFile());
}else {
throw FileException("文件后缀名不匹配错误:->${0}", filePath);
}
}else {
throw FileException("找不到文件错误:->${0}", filePath);
}
} catch (Exception e) {
throw FileException(e, "文件解析Domcument错误:->${0}", filePath);
}
}