Dobby
Dobby

Reputation: 225

Conflict in relative file name path in eclipse

In my application I am reading an XML file(say ABC.xml) which is in the WebContent/META-INF folder and parsing it using DOM parser as below

File xmlFile = new File("WebContent//META-INF//ABC.xml");
parser.parse(new InputSource(new FileReader(xmlFile.getAbsolutePath())));

Its showing file not found exception and when I print the xmlFile.getAbsolutePath() Its showing

D:\Softwares\SDE_7\eclipse\WebContent\META-INF\ABC.xml

This is where my eclipse setup is located

So I tried to use the same logic in simple java program and print the absolute path where it shows the correct path(project folder structure) and the program works fine

D:\GME_WorkSpace\Practice_1\WebContent\META-INF\sample.xml

Why is this conflict? How can I rectify it?

Upvotes: 0

Views: 654

Answers (2)

DAB
DAB

Reputation: 1873

If you're talking about WebContent, it sounds like you've written a Servlet.

In that case you should be using ServletContext to find your files.

getServletContext().getRealPath(...) will get the full OS path for a relative file name in your Servlet.

getServletContext() can be called from any class that inherits from HttpServlet.

Upvotes: 1

Biswajit
Biswajit

Reputation: 2516

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
URL url = classLoader.getResource("WebContent//META-INF//ABC.xml");
File file = new File(url.toURI());

Upvotes: 0

Related Questions