Archive

Posts Tagged ‘XML’

How to load an XML file from the classpath

February 4, 2009 Leave a comment

Saagar writes the following on his blog:

Today, I faced this issue in Java coding. I needed to load an XML file which was in my classpath but not in the same directory as the classes. The deliverable was a jar and the properties and the configuration XML files were in a different folder and were appended to the classpath at the runtime. The issue was that the file could not be located through the the statement

String fileName = getClass.getSystemResource(“config.xml”).getFile;

Then I thought that it checks relative to the current class and so used the statement

String fileName = ClassLoader.getSystemResource(“config.xml”).getFile;

But then, it wouldn’t still recognize the file. The reason is the same, it checks relative to the classes folder. I did not want to get the classpath from the system and browse through it for the config file since the class path could get larger. A couple of google searches and a little research later, I found the solution. The workaround is by using the following statement

String fileName = Thread.currentThread().getContextClassLoader().getResource(“config.xml”).getFile;

It only makes sense since in the above statement, you get hold of the context class loader and find the path in the entire classpath…

Categories: Java Tags: , ,
Follow

Get every new post delivered to your Inbox.