In file handling we most of the times need to locate a file from classpath. Though locating a file is not a rocket science but still I have seen people getting stuck doing this and ultimately hardcoding the file path at the required place.
Following is a code snippet which locates a file from classpath and returns its absolute path.
ClassLoader loader = Thread.currentThread().getContextClassLoader();
URL url = loader.getResource(“name_of_file.extension”);
String file = url.getFile().replace(“%20″, ” “);//this is required as URL treats space //as %20.
Some of the IO APIs of Java takes URI also as input, so URL can be converted to URI using url.toURI() method.