在我的Spring静态资源上读取文件始终为null

时间:2018-07-12 09:57:57

标签: java spring spring-mvc inputstream

有人可以解释一下我如何在静态资源下读取jrxml作为输入流。

这是我重新注册的资源路径

registry.addResourceHandler("/resources/**").addResourceLocations("WEB-INF/resources/");

在资源下,我有“报告”文件夹,在报告下,我有samplereport.jrxml

我使用这些代码,但总是抛出filenotfound异常

Resource resource = new ClassPathResource("/reports/samplereport.jrxml");
    InputStream resourceInputStream = resource.getInputStream();

我尝试了一下,并将我的samplereport.jrxml移动到了我的类的相同路径上,并且可以正常工作。

InputStream employeeReportStream
      = this.getClass().getResourceAsStream("/samplereport.jrxml");

但是我不想以这种方式工作。预先谢谢你。

3 个答案:

答案 0 :(得分:1)

在报告下方删除斜杠,如下面的代码。

Resource resource = new ClassPathResource("reports/samplereport.jrxml");

请参阅以下URL,以获取有关加载文件的更多信息。

https://www.mkyong.com/java/java-read-a-file-from-resources-folder/

How do I load a file from resource folder?

答案 1 :(得分:0)

您可以使用ResourceUtils类来读取文件系统中文件的资源位置。

File file = ResourceUtils.getFile("classpath:reports/file1.txt")

 //File is found
System.out.println("File Found : " + file.exists());

//Read File Content

String content = new String(Files.readAllBytes(file.toPath()));

System.out.println(content);

但是,如果您使用的是Spring,那么只有ResourceUtils类是有帮助的。(java.lang.Object.org.springframework.util.ResourceUtils

答案 2 :(得分:0)

您可能在此路径中犯了错误:

matplotlib.collections.PathCollection

代替

autoscale_view()