Spring-boot中获取路径(十二)

前言

Spring-boot中获取路径的一般方式

一、SpringBoot读取Resource下文件的几种方式

需求:提供接口下载resources目录下的模板文件,(或者读取resources下的文件)给后续批量导入数据提供模板文件。

方式一:ClassPathResource 

//获取模板文件:注意此处需要配置pom.xml文件;因为spring-boot默认只会读取application.yml配置文件
        ClassPathResource classPathResource = new ClassPathResource(examplePath);
        File file = null;
        try {
            file= classPathResource.getFile();
        } catch (IOException e) {
            e.printStackTrace();
        }

模板文件位置

坑1:找不到模板文件staffTemplate.xlsx。
原因:maven默认只编译默认配置文件格式的文件,如yml。
解决:pom.xml 增加下面配置

 <build>
      <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.yml</include>
                    <include>**/*.xlsx</include>
                </includes>
            </resource>
        </resources>
    </build>

坑2:中文文件名下载后无法正常显示。
解决:将中文编码

将
response.setHeader("Content-Disposition", "attachment;fileName=批量上传用户模板.xlsx");
//String fileName=new String("批量上传用户模板".getBytes(), StandardCharsets.ISO_8859_1);
改为
response.setHeader("Content-Disposition", "attachment;fileName=" + new String("批量上传用户模板".getBytes(), StandardCharsets.ISO_8859_1)
                    + ".xlsx");

参考链接:https://blog.csdn.net/weixin_42410936/article/details/106126377

问题:我通过这种方式,在本地可以找到路径,升到测试环境就不可以了。

二、ResourceUtils的用法

搜索关键词:

ResourceUtils读取properties文件  

ResourceUtils.getURL()用法及实例

参看链接:

https://www.cnblogs.com/qlqwjy/p/7530715.html 

https://www.cnblogs.com/szrs/p/15207672.html

如果错过太阳时你流了泪,那你也要错过群星了。
在所有的矛盾中,要优先解决主要矛盾,其他矛盾也就迎刃而解。
不要做个笨蛋,为失去的郁郁寡欢,聪明的人,已经找到了解决问题的办法,或正在寻找。
原文地址:https://www.cnblogs.com/szrs/p/13793940.html