Reputation: 437
I have a Spring Boot application. The code that needs to access a file is under the /resources/templates
directory.
The property from my application.properties
file that I'm trying to read is given below:
pont.email.template.location=templates/mailTemplate.html
The above property that I'm trying to access via @Value
in one of the @Component
class is given below:
@Value("${pont.email.template.location}")
private String templateLocation;
Now, I have this code given below which takes the template location and tries to read it via BufferedReader
.
BufferedReader reader = new BufferedReader(new FileReader(templateLocation));
Now, the value containing the file location is getting picked up properly by @Value
from application.properties
.
But the problem is that the application is not able to find templates/mailTemplate.html
.
The error that I'm getting is given below:
java.io.FileNotFoundException: templates/mailTemplate.html (No such file or directory)
Note: I have checked that mailTemplate.html
is present under the /resources/templates
directory.
How to resolve this issue?
Upvotes: 5
Views: 50271
Reputation: 124526
You cannot read a File
from inside a JAR. This fails due to the fact that the File
has to point to an actual file resource on the file system and not something inside a JAR.
Let Spring do the heavy lifting and use the Resource
abstraction to hide the nasty internals. So instead of using a String
use a Resource
and prefix the value of the property with classpath:
to make sure it is loaded from the classpath. Then use an InputStreamReader
instead of FileReader
to obtain the information you need.
@Value("${pont.email.template.location}")
private Resource templateLocation;
----------------
BufferedReader reader = new BufferedReader(new InputStreamReader(templateLocation.getInputStream()));
In your application.properties
prefix with classpath:
.
pont.email.template.location=classpath:templates/mailTemplate.html
Now it should work regardless of the environment you are running in.
Upvotes: 11