30Mar/102
Getting Path To Resource With ClassLoader
There is an easy way find a path to a resource using the ClassLoader, if desired resource is located within a project:
String getPathToResourceFile(String resourceName) {
URL url = getClass().getClassLoader().getResource(resourceName);
try {
return URLDecoder.decode(url.getPath(), Charset.defaultCharset().name());
} catch (Exception e) {
e.printStackTrace();
return url.getPath();
}
}
,
instead of return url.getPath();
UPD: As correct noticed dm3 user, just calling url.getPath() will have problems with spaces in the path. Applying URLDecoder.decode will solve the problem.
March 31st, 2010 - 20:24
Don’t forget that the path will be url escaped (as it’s an URL after all) so if you have spaces in the path, they’ll show as %20. Here’s a nice showcase of the error in action: http://webtest-community.canoo.com/jira/browse/WT-530.
URLDecoder.decode(url.getPath(), Charset.defaultCharset().name()) should suffice.
March 31st, 2010 - 20:37
Thanks!
I will check that out next week and update post accordingly.