0

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

Luke J
  • 1
  • 1
  • Does the image need to be in resources? Or do you have multiple images that get add dynamically? – Herry Sep 21 '22 at 08:18
  • 1
    Because it isn't a file but a classpath resource. Files from inside the classpath (and thus inside a jar at runtime) you cannot access as a `File`. Use a `new ClassPathResource("/images/logo.jpg");` and use the `getInputStream()` to read it. – M. Deinum Sep 21 '22 at 08:23

3 Answers3

1

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
  }
}
Herry
  • 365
  • 1
  • 14
1

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.

Lunatic
  • 1,519
  • 8
  • 24
  • 1
    Be careful with the getFile() method though. If there is no actual file in the classPath at runtime you might get a FileNotFoundException. Reading the InputStream is fine though. – Herry Sep 21 '22 at 08:24
  • @Herry correct ! i point out the the link for inputStream practice already. – Lunatic Sep 21 '22 at 08:28
0
  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());
Hai Mai
  • 39
  • 3