String Boot getting a resource file

时间:2017-10-30 15:33:56

标签: java spring spring-mvc spring-boot file-io

I have a Spring Boot app. that contains this file:

resources/metrics/telefonica/Metrics.xlsx

and in the code:

@Value(value = "classpath:/metrics/telefonica/Metrics.xlsx")
private Resource telefonicaMetricsTemplate;

..

Workbook wb = 
            WorkbookFactory.create
            (telefonicaMetricsTemplate.getInputStream());

But I got this error:

Caused by: java.io.FileNotFoundException: class path resource [metrics/telefonica/Metrics.xlsx] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/Users/lopes/Documents/workspace-sts-3.9.0.RELEASE/telefonicaUtils/target/telefonicaUtils-0.0.1-SNAPSHOT.jar!/BOOT-INF/classes!/metrics/telefonica/Metrics.xlsx
    at org.springframework.util.ResourceUtils.getFile(ResourceUtils.java:217)

I also tried Resource telefonicaMetricsTemplate = new ClassPathResource("/metrics/telefonica/Metrics.xlsx"); with the same result

I am running the app. from the command line as follows:

java -jar target/telefonicaUtils-0.0.1-SNAPSHOT.jar

I running the app. from Eclipse and it works fine

2 个答案:

答案 0 :(得分:1)

由于您正在硬编码资源路径,因此您不需要任何依赖注入。只需将您的资源初始化为ClassPathResource

private Resource telefonicaMetricsTemplate = new ClassPathResource("/metrics/telefonica/Metrics.xlsx");

答案 1 :(得分:0)

您是否尝试将classpath:...替换为file:...并指定绝对路径?

另外,我知道有一个用于处理Microsoft文档的Apache API。您可以将它与Spring Boot应用程序一起使用,并创建自己的Resource bean:https://poi.apache.org/

用法示例:https://www.concretepage.com/apache-api/read-write-and-update-xlsx-using-poi-in-java