开发者

Java: how to verify image file on localhost exists

开发者 https://www.devze.com 2023-01-16 11:35 出处:网络
This is driving me bonkers. I\'m writing a web app in Java and all I want to do is verify the existence of an image that\'s saved to an /images folder right under the web root.

This is driving me bonkers. I'm writing a web app in Java and all I want to do is verify the existence of an image that's saved to an /images folder right under the web root.

The 1,000,000 google searches I did seemed to indicate that the File.exists(path) method is the way to go. But for obvious reasons, I don't want to hard code the path.

Physically, the test image file I'm working with exists on my D-drive at, let's say, D:\documents\images\myimage.jpg. GlassFish is my local server and I don't think my image files are replicated to a "GlassFish folder" when my app i开发者_开发技巧s deployed, so I think the only physical copy is the one on the D: drive.

The only way I can get:

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

to return TRUE is using the string "D:\documents\images\myimage.jpg". What I was after is a test like exists() that maybe uses a URL that I could couple with some other method or parameter that references the site root and I could build the rest of the URL relative to that.

Any help is much appreciated.


Since documents is the web root, you should be able to use the ServletContext.getRealPath(String) method.

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


Maybe you can put your images in the war file and use getResourceAsStream to get the file?

In that case the path would be relative to the root of the war file

0

精彩评论

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