springboot死活读取不到src.main.resources下的文件FileNotFoundException

325 阅读1分钟

在springboot项目中加载src.main.resources下的静态文件,但是一直报FileNotFoundException异常,

java.io.FileNotFoundException: class path resource xxx cannot be opened because it does not exist

代码如下:

ClassPathResource resource=new ClassPathResource("filename");
InputStream is=resource.getInputStream();  //此处抛FileNotFoundException
String content=new String(ByteStreams.toByteArray(is));

项目结构:

src
--main
----java
----resources
------filename  #要读取的文件

文件编码,文件权限都试了还是不行。但是这段代码在另外一个项目里面运行的完美无瑕,这时候就怀疑到了可能是项目配置的问题,经过配置文件多处排除发现和程序配置无关(classpath配置啥的)。

最后还是回归该问题最本质的之处,文件找不到,但是项目里面该文件板板正正的放在那里,所以到java运行的文件里去找(遇到奇怪问题的时候多想想class文件),发现了问题所在编译后的classs文件夹下确实没有。到这里基本就定位到问题了,编译出了问题。

打开pom.xml文件

<build>
    <resources>
        <resource>
            <directory>src/main/resources</directory>
            <filtering>true</filtering>
            <includes>
                <include>**/*.yml</include>
                <include>**/*.xml</include>
            </includes>
        </resource>
    </resources>
</build>

原来项目的pom文件里面指定了xml和yml后缀的文件才会放到编译目录里面,可以加上自己要读取文件的后缀,或者把这个resources配置项移除,就可以了。