springboot获取根目录及资源路径及解决jar发布时的出现D:/export-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/static

测试项目的文件目录

1.获取文件根目录

String property = System.getProperty("user.dir");

输出结果为:

D:\DocumentH\PDFExport

 

2.获取资源路径(比如获取resources下的temp文件夹路径hello.ftl文件)

   try {
            File file = ResourceUtils.getFile("classpath:static\\temp");
            System.out.println(file.getPath());
            System.out.println(file.isDirectory());

            System.out.println("-----------------------------------------------------");

            File helloFile = ResourceUtils.getFile("classpath:static\\temp\\hello.ftl");
            System.out.println(helloFile.getPath());
            System.out.println(helloFile.isDirectory());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

输出结果为:

D:\DocumentH\PDFExport\target\classes\static\temp
true
-----------------------------------------------------
D:\DocumentH\PDFExport\target\classes\static\temp\hello.ftl
false

3.第2种方式在idea环境下获取资源路径没问题,但是将项目打成jar包,再运行就会出现如下问题:

java.io.FileNotFoundException: class path resource [static] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/D:/export-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/static

发现找不到,而且在D:/export-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/static中间有!莫名其妙的出现

百度了好久大概意思是:在idea环境下,资源文件都以正常的磁盘路径存储;但是当打成jar包,该文件是存在jar包文件资源里,而不是真实存在于磁盘路径上。

而此时,我们需要换一种方式即:

InputStream inputStream=this.getClass().getResourceAsStream("/static/temp/hello.ftl");

可以将文件获取到,不过是以流的形式,然后我们可以将流转成我们自己想要的格式,下面的示例是转为File格式。

需要引入commons-io包

String property = System.getProperty("user.dir");
//在根目录生成一个文件
File targetFile = new File(property+"targetFile.ftl");
//将流转成File格式
FileUtils.copyInputStreamToFile(inputStream, targetFile);

再打包,掉接口,就没什么问题了。

建议:为了避免在发布的时候遇到各种坑爹问题,所以还是建议使用第三种。

  • 3
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值