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

标签 java servlets

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

我进行的 1,000,000 次谷歌搜索似乎表明 File.exists(path) 方法是可行的方法。但出于显而易见的原因,我不想对路径进行硬编码。

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

我能得到的唯一方法:

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

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

非常感谢任何帮助。

最佳答案

由于 documents 是网络根目录,您应该能够使用 ServletContext.getRealPath(String) 方法。

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).

关于Java:如何验证本地主机上的图像文件是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3740113/

相关文章:

java - JSP中如何知道远程IP地址

Java:静态初始化 block 中的方法比主方法中的方法慢

java - 如何处理数字格式异常并将 int/double 变量替换为默认值 0/0.0?

java - JPQL - JPA 实体集合成员中所有项目的列表

java - Servlet 不会重定向我

java - spring httpsession 和 tomcat session 的区别

java - 渲染 HTML : Serverside Vs Clientside

java - 创建文件夹

php - 使用 PHP 下载 JSON 的移动应用程序

java - 将动态形成的 Servlet(名称)重定向到静态 Servlet