Spring-Boot获取部署项对jar中内容获取的一些思考

SpringBoot项目打包是jar的方式,在实际项目部署也是以jar的形式.jar部署项目有比较特殊,不会解压jar中的文件,jar的目录结构如下:

                                                                    

                                        BOOT-INF

                                        |            ---classes

                                        |            ----lib

                                        META-INF


其中classes下是配置文件所在的路径,lib是springboot所依赖的jar会全部放在此目录夹下面!


例如,部署的项目发布在:E://vodtest.jar,后面的代码都会以这个为例子。

String path = ClassUtils.getDefaultClassLoader().getResource("").getPath();
System.out.println("path:" + path);

打印结果是:file:/E:/vodtest.jar!/BOOT-INF/classes!/


File pathTest = new File(ResourceUtils.getURL("classpath:").getPath());
System.out.println("pathTest1 :" + pathTest.getAbsolutePath());
if(!pathTest.exists()) {
     pathTest = new File("");
     System.out.println("pathTest2 :" + pathTest.getAbsolutePath());
}
System.out.println("pathTest3: "+pathTest.getAbsolutePath());   //SpringBoot jar 所在的目录

打印结果分别是:

pathTest1 :e:\\file:\E:\vodtest.jar!\BOOT-INF\classes!
pathTest2 :e:\

pathTest3: e:\


有个需求:要获取classes中的配置文件的内容,如何获取?

InputStream stream = getClass().getClassLoader().getResourceAsStream("ccupload-1.0.0.jar");
File targetFile = new File("D://accupload-test.jar");
FileUtils.copyInputStreamToFile(stream, targetFile);
getResourceAsStream()这个方法能获取到文件的流信息,springboot项目发布的jar的方式,我们无法通过File的路径方式获取到文件的信息,通过当前class所在的目录获取到下面文件的流信息,可以间接的获取到classes中配置文件的内容。


猜你喜欢

转载自blog.csdn.net/fengchao2016/article/details/79391896