2017-04-16 677 views
0

使用Spring Boot。我正在尝试使用Apache POI库解析项目中本地存储的excel文件。我的目录结构如下所示:Spring Boot无法使用ClassPathResource查找文件

  • SRC

    • 主要

      • 的Java

        • com.app
          • 控制器
          • 车型
          • 库< - 我从这里
      • 资源

        • 静态
          • Test.xlsx <呼吁 - 我想访问此

File excel = new ClassPathResource("Test.xlsx").getFile(); 

File file = new File(classLoader.getResource("src/main/resources/static/test.xlsx").getFile()); 

我已经尝试上述两种方式访问​​该文件,我已经尝试的路径很多变化的文件,但没有任何工作。我没有得到构建错误或运行时错误,该文件是根本找不到,当我尝试调用该方法时,我得到该行上的NullPointerException。

+1

想这[文章](http://stackoverflow.com/questions/36371748/spring-boot-access-static-resources-missing-scr -main-resources)可能为您提供解决方案。 –

+0

@RajithPemabandu我已经尝试了该帖子提出的解决方案,但仍然没有找到 – arbabk

回答

0

supoose你只覆盖扩展WebMvcConfigurerAdapter

@Override 
public void addResourceHandlers(final ResourceHandlerRegistry registry) { 
    registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); 
} 

这是一个博客张贴关于Spring资源@Configuration类的addResourceHandlers方法 - here

看看春天documentation了解更多详情。

+0

我没有使用Spring MVC我只是简单的设置。这也可以通过在application.properties中添加“spring.mvc.static-path-pattern =/resources/**”来实现吗? – arbabk

+0

是的。但愿如此。 –

+0

它没有工作...... – arbabk

0

我相信你的情况下,正确的是

new ClassPathResource("/static/Test.xlsx").getFile() 
+0

莫名其妙地不起作用 – arbabk