chk.buddi
chk.buddi

Reputation: 603

How to get relative path of a image file

I need to get relative path of a certain image(add.png) file in my eclipse project. Print screen has been attached.

enter image description here

My java class path is the src/main/java/com/abc/controller/myClass.java

Upvotes: 0

Views: 2057

Answers (3)

djeikyb
djeikyb

Reputation: 4589

Try using the classloader object.

ClassLoader loader = Thread.currentThread().getContextClassLoader();

This will let you access files on the classpath. Look at the getResource method that returns a URL.

I notice in your screenshot that eclipse is not categorizing "src/main/webapp" under "Java Resources". I think this means eclipse is not putting that webapp folder in your classpath. You may need to configure the eclipse build path. In brief, right-click on the project, click properties, click "build path" on the left, select the "source" tab, and add "src/main/webapp".

Upvotes: 1

Braj
Braj

Reputation: 46841

The relative path starts from /.

If you are accessing the image in JSP file then you can try with core tag library.

for example:

<%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:url value="/images/add.png"/>

If you want to access the image file at server side then put the file under resources folder that goes directly to classpath.

You can try with Spring ClassPathResource to read the resources from classpath that are stored directly under resources folder.

For example:

    try (InputStream in = new ClassPathResource("/images/add.png").getInputStream())
    {
        ...
    }
    catch (IOException e)
    {
        ....
    }

Upvotes: 0

Juned Ahsan
Juned Ahsan

Reputation: 68715

It depends on your classpath entries in your eclipse. As it seems to be a maven project, so most likely your webapp directory should be part of classpath. And if that is the case, then relative url for your file will start from directory images,like this:

images/add.png

Upvotes: 0

Related Questions