Spring boot Resource getFile() is not working

Viewed 1356

In my spring boot project I am trying to load an xml file located in resources folder. If I try loading file with

Resource resource= resourceLoader.getResource("classpath:" + filepath);
File tempFile = resource.getFile();

I get following error in docker container where as the file is present in BOOT-INF\classes folder in jar file (packing type is jar)

Exception occur while generating mock sso response java.io.FileNotFoundException: class path resource [mock_sso_response.xml] cannot be resolved to absolute file path because it does not reside in the file system: jar:file:/polst-webapp-2.1.5-SNAPSHOT.jar!/BOOT-INF/classes!/mock_sso_response.xml

However using getInputStream works.

Resource resource= resourceLoader.getResource("classpath:" + MOCK_SSO_RESPONSE_FILE);
InputStream inputStream = resource.getInputStream();

It would be really helpful if someone could share the reason behind this and also is there any better/alternate way to load xml files in spring boot. Any help would be much appreciated

1 Answers

From the Spring Resource JavaDoc

Throws: FileNotFoundException - if the resource cannot be resolved as absolute file path, i.e. if the resource is not available in a file system

So it seems the implementation of Resource just doesn't support the usage of getFile(). Usually you want to check with isFile() if the resource can be resolved via getFile().

Related