Tuesday, July 13, 2010

Java File Loading in Web Application

Different applications, different technologies, different designs, different packaging, different servers, different developers... Everything is different in web applications the loading of files becomes really difficult.

So how does one load files (with relative path / with absolute path) in the project structure in their java code within web applications.



1) Get the real path of the file from ServletContext or HttpServletRequest
ServletContext sc = (ServletContext)context;
sc.getRealPath("temp.txt");

or

HttpServletRequest hsrTemp = (HttpServletRequest)context;
hsrTemp.getRealPath("temp.txt");

2) Try with context path
HttpServletRequest hsrTemp = (HttpServletRequest)context;
File fileTemp = new File(hsrTemp.getContextPath()+"/resources/temp.txt");

3) Input stream - file in classes folder
InputStream inpStrTemp = this.getClass().getResourceAsStream("temp.txt");

4) resource url - file in classes folder
URL urlTemp = this.getClass().getResource("temp.txt");

5) Try this one.....................the magic one :) (all four above failed for me, this worked and yes I wrote it on my own ...)

URL currentClassFolder = TestClass.class.getResource(""); //this gives you the package reference of the test class
String pathFromUrl = currentClassFolder.getPath(); //this gives the actual path
String finalPath = pathFromUrl.substring(0,pathFromUrl.indexOf("WEB-INF/classes/com/test/web/")); //navigate to where ever you want to
finalPath = finalPath.replaceAll("% 20", " "); //command prompt doesn't like % 20'

Hope it helps, if it does - do leave a comment!

m.m

No comments: