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 HttpServletRequestServletContext sc = (ServletContext)context;
sc.getRealPath("temp.txt");
orHttpServletRequest hsrTemp = (HttpServletRequest)context;
hsrTemp.getRealPath("temp.txt");
2) Try with context pathHttpServletRequest hsrTemp = (HttpServletRequest)context;
File fileTemp = new File(hsrTemp.getContextPath()+"/resources/temp.txt");
3) Input stream - file in classes folderInputStream inpStrTemp = this.getClass().getResourceAsStream("temp.txt");
4) resource url - file in classes folderURL 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