in a spring boot application, i have an image: src/main/resources/images/logo.jpg
I need to use that image creating new File, but this doesn't work:
File img = new File("/images/logo.jpg");
How can i do this?
Thankss
CodePudding user response:
The resources folder should be in your classpath. This means you can access it like this:
@Service
class SomeClass {
@Value("classpath:images/logo.jpg")
private Resource img;
private void methodThatUsesImage() {
// you can do something here with the InputStream of img
}
}
CodePudding user response:
- new File("/images/logo.jpg");
java will look up in the "working directory/images/logo.jpg". it does not exist, right?
- Your file is in src/main/resources so the correct is
URL url = this.getClass().getClassLoader().getResource("/images/logo.jpg");
File file = new File(url.getFile());
CodePudding user response:
There are different ways to load resource files, one practice is as follow
ClassLoader cl = getClass().getClassLoader();
File file = new File(cl.getResource("images/logo.jpg").getFile());
And in spring based project you can use
...
ClassPathResource resource = new ClassPathResource("images/logo.jpg");
...
For not facing FileNotFoundException
at runtime please see the attached link as well.