en Lopes
en Lopes

Reputation: 2133

String Boot getting a resource file

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

Upvotes: 1

Views: 769

Answers (3)

JMetamorphe
JMetamorphe

Reputation: 1

It works in Eclipe as Eclipse can see what files are in your resources folder. But if the folders in your "src/main/resources" folder is NOT in the jar OR is NOT in the classpath (iex : your folder "/metrics" is next to the jar), the jvm cannot find it when u throw it in command Line.

Upvotes: 0

tmarwen
tmarwen

Reputation: 16364

Since you are hardcoding you resource path, you ain't need any dependency injection. Just initialize your resource as a ClassPathResource:

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

Upvotes: 2

Blake
Blake

Reputation: 1327

Did you try replacing classpath:... with file:... and specifying an absolute path?

Also, I know there is an Apache API for handling Microsoft documents. You can use it with your Spring Boot app and make your own Resource bean: https://poi.apache.org/

example of usage: https://www.concretepage.com/apache-api/read-write-and-update-xlsx-using-poi-in-java

Upvotes: 0

Related Questions