Developers, Developers, Developers! Maksim Sorokin IT Blog

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.

Tagged as: Leave a comment
Comments (2) Trackbacks (0)
  1. 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.

  2. Thanks!
    I will check that out next week and update post accordingly.


Leave a comment


Trackbacks are disabled.