How to get absolute path of a file in Servlet?

In a web application, you may be often faced with a requirement to get the absolute path of a file location from a relative path name.

There is a simple solution to get the absolute path in servlet/struts/springs. Use the following code

String absolutePath = getServletContext().getRealPath("<relativePath>");

This is required because there may be scenarios where you want to access a file inside the WEB-INF folder in the service layer(java bean)of your web application. You can get Real path from Servlet context and then pass the same to service layer. If you want to access the file in Servlet you can use only the relative path.

Search