0
点赞
收藏
分享

微信扫一扫

springboot获取文件路径

月白色的大狒 2022-01-04 阅读 99
1    this.getClass().getResource("/static/index.html").getPath()

注意:this.getClass().getResource("/")和this.getClass().getResource("")的区别:

 

 

采用spring中的方式:

@Autowired
ResourceLoader resourceLoader;

//resourceLoader.getResource("/static/index.html")写法在这是错误的

resourceLoader.getResource("classpath:static/index.html").getURL().getPath();

还有一种获取方法:

new ClassPathResource("/static/index.html").getURL().getPath()

2 加载resource文件夹下的文件

this.getClass().getResource("data.xlsx").getPath() //这样在idea下是没问题的,打完包就会出问题,因为target的内容都在jar包里,文件的路径已经不存在了。
此时正确的取法是: 
InputStream inputStream= this.getClass().getClassLoader().getResourceAsStream("data.xlsx");
举报

相关推荐

0 条评论