因为jar包中的文件不能用读取普通文件的方法读取,java提供了专门读取jar包文件的类,及JarFile类,使用如下:
InputStream inputStream = null;
try {
String path = this.getClass().getProtectionDomain().getCodeSource().getLocation().getPath();
URL url = new URL("jar:file:" + path + "!/" + "resources/mybatis-config.xml");
inputStream = url.openConnection().getInputStream();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
其中path为jar包在磁盘中的位置,eg:"E:/mavenReposity/shiro-api-1.0.jar"
"resources/mybatis-config.xml"为要读取的文件在jar包中的位置