Wednesday, July 16, 2008

Java: Loading an XML file from the CLASSPATH

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...

12 comments:

Kamal said...

Thanks for sharing.

Anonymous said...

getResourceAsStream() returns an InputStream, which has no getFile() method.

Saagar said...

@abdul,
You are right, it was a type, it should have been getResource("config.xml").getFile. getResource() returns a URL that has a getFile method..

schup said...

If you don't want the resource to be relative to the current class you can use getClass().getResource("/config.xml")
This looks in the root of the class path (using the same classloader)

If you use getResourceAsStream() you wouldn't be confied to just files but the config.xml could also be in a jar file.

Geert Schuring said...

Thanks for this!

Anonymous said...

Thanks for sharing the nice document.

Unknown said...

Number one! Great solution.

Thanks a lot.

ashish said...

Thanks, this was useful.

Unknown said...

For more compatibilty beetwen OS file system, it's better to use:

this.getClass().getClassLoader().getResourceAsStream("yourFileName")

Anonymous said...

String filename = ClassLoader.getSystemClassLoader().getResource(yourFile).getFile();
works fine.

Anonymous said...

Good job man.
I've been needing that snippet for a while.

"thumbs up"

Anonymous said...

Thanks so much