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
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
}
}
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.
java will look up in the "working directory/images/logo.jpg". it does not exist, right?
URL url = this.getClass().getClassLoader().getResource("/images/logo.jpg");
File file = new File(url.getFile());
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.