tags:

views:

54

answers:

2

How to get image path in java ?

I am using eclipse, i want to display the image in jsp,I want to give path like "/images/logo.jpg" but it is getting nullpointer exception when execute the page.

if i give fullpath , it is working like "d:/project/images/logo.jsp".How to get display the image with absolute path ?

+1  A: 

Instead of /images/logo.jpg put images/logo.jpg i.e. remove the first slash.

eugener
Image image = Image.getInstance("images/logo.jpg");This code inside pdf generation using itext.
Rose
Then you have to do something like URL imgURL = getClass().getResource("images/logo.jpg");Image img = new ImageIcon(imgURL).getImage();
eugener
A: 

You should avoid using relative paths in java.io stuff as much as possible. Any relative path will be relative to the current working directory which is dependent on the way how you started the application and is uncontrollable from inside the code. When started as e.g. a Tomcat service, it will be relative to c:/path/to/tomcat/bin. When running in Eclipse, it will be relative to c:/path/to/eclipse/project/bin. When running in command console, it will be relative to currently opened folder. Etcetera. You don't want to be dependent on that. Bad idea.

In case of JSP/Servlet webapplications there are basically two ways to obtain an absolute resource path using a relative path in a reliable way:

  1. Retrieve it from the runtime classpath (there where all the classes and libraries are):

    ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    String path = classLoader.getResource("/images/logo.jpg").getPath();
    
  2. Retrieve it from the webcontent (there where all the JSP files and /WEB-INF folder are):

    ServletContext context = getServletContext(); // Inherited from HttpServlet.
    String path = context.getResource("/images/logo.jpg").getPath();
    
BalusC