Home > Java > How to load an XML file from the classpath

How to load an XML file from the classpath

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…

Advertisements
Categories: Java Tags: , ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: