Home > Back-end >  Spring boot images in src main resourcer aren't visible from java code
Spring boot images in src main resourcer aren't visible from java code

Time:09-21

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:

  1. new File("/images/logo.jpg");

java will look up in the "working directory/images/logo.jpg". it does not exist, right?

  1. 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.

  • Related