开发者

How to get image absolute path?

开发者 https://www.devze.com 2023-01-06 00:17 出处:网络
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 except开发者_JS百科ion when execute

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 except开发者_JS百科ion 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 ?


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();
    

If all you ultimately want is an InputStream out of it, which you perhaps intented to create using new FileInputStream(path), then you should be using getResourceAsStream() methods instead:

  1. From classpath:

    InputStream content= classLoader.getResourceAsStream("/images/logo.jpg");
    
  2. Or webcontent:

    InputStream content = context.getResourceAsStream("/images/logo.jpg");
    


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

0

精彩评论

暂无评论...
验证码 换一张
取 消