0

In my Java tomcat application, I'm facing problems trying to get the correct file path.

Two code snippets from my Java app I need:

try {
        InputStream in = getClass().getResourceAsStream("StaticContent/images/image.png");

        image = ImageIO.read(in);
    } catch (Exception e) {
        System.out.print(e.getStackTrace());
    }

Second snippet:

DataSource fds_image = new FileDataSource
                ("StaticContent/images/image.png");

I have put the image into the folder:

src/main/webapp/StaticContent/images/image.png

Folder structure

I have tried several ways to make sure the file path is correct, but nothing worked. Also, I put the image into the ressources folder and tried different paths but to no avail. I assume that I choose the wrong (relative) path, but I don't know how to handle it.

Can anybody help me with this?

6006604
  • 7,577
  • 1
  • 22
  • 30
biro
  • 11
  • 3
  • Do you have a destination folder? If so, does it have the same structure? Are you packaging your program into a jar or similar? – Scratte Apr 21 '21 at 09:10
  • The application will be packed to war file with maven – biro Apr 21 '21 at 09:20
  • In your war file and in the deployed application directory on the Toncat server, is the file in the path `StaticContent/images/image.png`? – FrankPl Apr 21 '21 at 09:33
  • Yes, when I have a look into the folder structure of the war file, it's in there, but can't be found. I read something about context, do I have to do something in this direction? – biro Apr 21 '21 at 09:58
  • @biro: `StaticContent/images/image.png` is **not** a classpath resource, so you need to use [`ServletContext#getResourceAsStream`](https://jakarta.ee/specifications/platform/8/apidocs/javax/servlet/servletcontext#getResourceAsStream-java.lang.String-) instead. If you don't use servlets directly, please provide more details in your question. – Piotr P. Karwasz Apr 21 '21 at 10:41
  • Check [this answer](https://stackoverflow.com/q/2161054/11748454) – Piotr P. Karwasz Apr 21 '21 at 10:46
  • Thanks a lot Piotr, this works for me. – biro Apr 21 '21 at 20:59

0 Answers0