如何获取Jar包中文件
1.通过ClassLoader下的getResource
在java中获取resource文件一般可以通过 getResource 来获取,如果需要获取多个通过getResources
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
URL resource = contextClassLoader.getResource("test.txt");
System.out.println(resource.getPath());
idea中:
/D:/study/JarTest/target/classes/test.txt
Jar包中:
file:/D:/study/JarTest/target/JarTest-1.0-SNAPSHOT.jar!/test.txt
Jar中输出的路径不是常规的文件路径,所以通过File是无法获取的
2.JarURLConnection
JarURLConnection jarConnection = (JarURLConnection) resource.openConnection();
JarFile jarFile = jarConnection.getJarFile();
JarEntry jarEntry = jarConnection.getJarEntry();
InputStream in = jarFile.getInputStream(jarEntry);
try(BufferedReader r = new BufferedReader(new InputStreamReader(jarFile.getInputStream(jarEntry)));){
System.out.println(r.readLine());
}
老师老师,我这段代码在jar中运行是正常的,但是用idea 调试就报异常啊
sun.net.www.protocol.file.FileURLConnection cannot be cast to java.net.JarURLConnection
在调试时和jar中都能运行的代码
1.通过Url下的getProtocol
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
URL resource = contextClassLoader.getResource("test.txt");
//jar 包下 file:/D:/study/JarTest/target/JarTest-1.0-SNAPSHOT.jar!/test/JarTest.class
File rootDir = new File(resource.getPath());
System.out.println(resource.getPath());
if("file".equals(resource.getProtocol())){
String path = resource.getPath();
File file = new File(path);
FileInputStream in = new FileInputStream(file);
try(BufferedReader r = new BufferedReader(new InputStreamReader(in));){
System.out.println(r.readLine());
}
}else if ("jar".equals(resource.getProtocol())){
JarURLConnection jarConnection = (JarURLConnection) resource.openConnection();
JarFile jarFile = jarConnection.getJarFile();
JarEntry jarEntry = jarConnection.getJarEntry();
System.out.println(jarFile.getName());
System.out.println(jarEntry.getName());
try(BufferedReader r = new BufferedReader(new InputStreamReader(jarFile.getInputStream(jarEntry)));){
System.out.println(r.readLine());
}
}
这代码也太长了吧,有没有简单的啊!!!!
2.通过getResourceAsStream
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
InputStream in = contextClassLoader.getResourceAsStream("test.txt");
try(BufferedReader r = new BufferedReader(new InputStreamReader(in));){
System.out.println(r.readLine());
}
实际应用
手动向mybatis 注册xml
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
InputStream resourceAsStream = contextClassLoader.getResourceAsStream("mapper");
IoUtil.readUtf8Lines(resourceAsStream, (LineHandler) (xmlName)->{
InputStream in = contextClassLoader.getResourceAsStream(String.format("mapper/%s",xmlName));
XMLMapperBuilder xmlMapperBuilder = new XMLMapperBuilder(in, configuration, xmlName, configuration.getSqlFragments());
xmlMapperBuilder.parse();
});