Monday, March 28, 2011

How to read folder structure from resource path in Maven.

Today I had to read a directory structure from a folder in recourses folder of my Maven project and do some operations with it.

So my first try was
File myFolder = new File(MYFOLDERNAME);

Where MYFOLDERNAME was only the name of folder to read, without any path information. In this scenario I was getting a file that was in project's home directory, and not maven's customized resource directory as specified in Maven Standart Directory Layout.

So I decided to play around with getResource method from class loader, and I type the follwing:

File myFolder = new File(getClass().getResource(MYFOLDERNAME).getFile());

Which to my surprise throw a null pointer exception, cause getClass().getResource(MYFOLDERNAME) was returning null. Playing with getURI also did not help, until I typed

File myFolder = new File(getClass().getClassLoader().getResource(MYFOLDERNAME).getFile());

which made everything to magically work. I don't know why this worked, since I unfortunately don't have a strong knowledge of Java internals, such as ClassLoaders, however my wild guess is that Maven has its own class loader, so that's why this occurs.

Happy coding!

No comments:

Post a Comment