PDA

View Full Version : Getting web context path into java class


satyambdvp
12-23-2009, 09:53 AM
Hi,

I created a web application in Netbeans 6.8.In that I created a dao which is a normal java class.In my project I have a folder named /xmls in that folder I kept my xml files.But I am not able to access those files.It is taking the default into tomcat's bin folder and there it is saying that no xml file is there.

When I used struts(servlets) in before projects it is no problems at all as we have the request.getServletContext(); method and from there we can use the getRelaPath("/xmls/names.xml"); methods to get file.

As I am now using the normal java class and the file should be accessible to any person on his system,i kept the files in my project,I want to get the file to access in the java class.How it is possible?

Can we get the file into a normal java class?Please help me it is urgent.

my code is as below

my file is names.xml which is in xmls folder which is in my project root folder.

File xml = new File("./xmls/names.xml");
JAXBContext jContext = JAXBContext.newInstance("com.coredb");
Unmarshaller unmarshall = jContext.createUnmarshaller();
Name name = (Name) unmarshall.unmarshal(xml);

it is showing the below error

[java.io.FileNotFoundException: C:\apache-tomcat-6.0.18\bin\.\xmls\names.xml (The system cannot find the path specified)]

it is taking the below path

C:\apache-tomcat-6.0.18\bin\.\xmls\names.xml

brad211987
12-23-2009, 06:20 PM
Is this file static? or does it change?

If it doesn't change, you could put it on your classpath instead and load it from there.

You could also get your current directory with a file object, here is a quick guess:


File file = new File(".");
String currentDirectoryPath = file.getCanonicalPath();


Then you could use relative paths from there. If the location of the file changes from one execution to the next, I would suggest a file chooser or a properties file that points to the location in a property.

Hope that gives you some options.