如何获得图像的绝对路径? [英] How to get image absolute path?

查看:210
本文介绍了如何获得图像的绝对路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在Java中获取图像路径?

How to get image path in java ?

我正在使用eclipse,我想在jsp中显示图像,我想给出类似"/images/logo.jpg"的路径,但是在执行页面时却得到了nullpointer异常.

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.

如果我给出fullpath,它的工作方式类似于"d:/project/images/logo.jsp".如何显示具有绝对路径的图像?

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

推荐答案

您应尽可能避免在java.io内容中使用相对路径.任何相对路径都将相对于当前工作目录,这取决于您启动应用程序的方式,并且无法从代码内部进行控制.当开始时例如Tomcat服务,它将相对于c:/path/to/tomcat/bin.在Eclipse中运行时,它将相对于c:/path/to/eclipse/project/bin.在命令控制台中运行时,它将相对于当前打开的文件夹. Etcetera.您不想依赖于此.好主意.

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.

对于JSP/Servlet Web应用程序,基本上有两种方法可以可靠地使用相对路径来获取绝对资源路径:

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. 运行时类路径(在那里有所有类和库)中检索它:

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

  • webcontent (所有JSP文件和/WEB-INF文件夹所在的位置)中检索它:

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

  • 如果您最终想要的只是其中的InputStream,您可能打算使用new FileInputStream(path)创建,那么您应该使用getResourceAsStream()方法:

    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. 来自类路径:

    1. From classpath:

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

  • 或网站内容:

  • Or webcontent:

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

  • 这篇关于如何获得图像的绝对路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆