有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

servlets Java:如何验证本地主机上的映像文件是否存在

这让我发疯。我正在用Java编写一个web应用程序,我只想验证是否存在保存到web根目录下的/images文件夹中的图像

我所做的1000000次谷歌搜索似乎表明该文件。exists(path)方法是一条可行的道路。但出于显而易见的原因,我不想硬编码路径

实际上,我正在使用的测试映像文件存在于我的D-drive上,比如说,D:\documents\images\myimage。jpg。GlassFish是我的本地服务器,我认为在部署我的应用程序时,我的图像文件不会复制到“GlassFish文件夹”,因此我认为唯一的物理副本是D:驱动器上的

我能得到的唯一方法是:

boolean fileExists = new File(somePath).exists();

要返回TRUE,请使用字符串“D:\documents\images\myimage.jpg”。我所追求的是一个类似exists()的测试,它可能使用一个URL,我可以将该URL与引用站点根的其他方法或参数结合起来,然后我可以构建与之相关的URL的其余部分

非常感谢您的帮助


共 (2) 个答案

  1. # 1 楼答案

    因为文档是web根,所以您应该能够使用ServletContext。getRealPath(字符串)方法

    ServletContext context = servletRequest.getSession().getServletContext();
    // Or if you have the servlet instead of request, use this:
    // ServletContext = servlet.getServletContext(); // see comment by BalusC
    String virtualPath = "/images/myimage.jpg";
    String realPath = context.getRealPath(virtualPath);
    
    // realPath will be D:\documents\images\myimage.jpg
    

    http://download.oracle.com/javaee/5/api/javax/servlet/ServletContext.html#getRealPath(java.lang.String)

    Returns a String containing the real path for a given virtual path. For example, the path "/index.html" returns the absolute file path on the server's filesystem would be served by a request for "http://host/contextPath/index.html", where contextPath is the context path of this ServletContext..

    The real path returned will be in a form appropriate to the computer and operating system on which the servlet container is running, including the proper path separators. This method returns null if the servlet container cannot translate the virtual path to a real path for any reason (such as when the content is being made available from a .war archive).

  2. # 2 楼答案

    也许你可以把你的图像放到war文件中,然后用getResourceAsStream来获取文件

    在这种情况下,路径将相对于war文件的根