This week's book giveaway is in the OO, Patterns, UML and Refactoring forum. We're giving away four copies of Refactoring for Software Design Smells: Managing Technical Debt and have Girish Suryanarayana, Ganesh Samarthyam & Tushar Sharma on-line! See this thread for details.
programX calls my servlet that has been deployed on the server (Windows) (servlet8.war).
In my servlet, I'm trying to read a file that is present on the same server, and display the contents as output. In my program, I have hardcoded the path of the file (on the server), and it is actually working fine.
But I'm sure this is not the right way to go about, as the directory can change on the server (example: C: or F: or D . Is there a better way of coding for accessing a file on the server?
The ClassLoader.getResourceAsStream(String name) method will probably help you out here. It will find the specified file (by name) in your classpath and return an InputStream object to it. With this method you can put your file in any of the directories on your classpath (maybe even in your war's top-level dir) and the class loader will find it.
ServletContext.getRealPath(String path) will help you. But this method will return "null" when your web application is deployed as a war file. So if you want your web application to be portable then you got to use the following methods of ServletContext
I assume the resource you intend to access is NOT part of the WEB-INF/lib jar file(or) outside the web-application. If its the case then you got to use the following methods of java.lang.ClassLoader class.