classPathResource 读取resource文件夹下的文件失败

问题描述

最近在使用jasperReport 的过程中将模板文件放在resource文件下读取,使用ClassPathResource去读取却出现 文件找不到异常,而且更加奇怪的是它只对模板文件有影响

读取模板文件

 @Test
    public void test2() {
        ClassPathResource classPathResource = new ClassPathResource("template/pdf/PaperCover.jasper");
        try {
            InputStream in = classPathResource.getInputStream();
            int c;
            while ((c = in.read()) != -1) {
                System.out.println(c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

image.png

读取普通txt文件

@Test
    public void test2() {
        ClassPathResource classPathResource = new ClassPathResource("template/pdf/t1.txt");
        try {
            InputStream in = classPathResource.getInputStream();
            int c;
            while ((c = in.read()) != -1) {
                System.out.println(c);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

image.png

这是为啥呢?希望帮我解答一下

阅读 4.1k
1 个回答

感觉不像代码上的问题。

你可以先看一下编译后target文件夹下有没有这个文件,resources文件夹中内容默认是在target/classes中。所以你可以先看一下target/classes/template/pdf/PaperCover.jasper是否存在。

如果不存在的话,一种可能性是idea的bug,那就清缓存重启。另一种可能性是maven在编译时没有包含这个文件,这种可以在pom文件的build下加以下内容试一下。

        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.*</include>
                </includes>
            </resource>
        </resources>
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题