Getting a file from classpath

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.

– Kamlesh


2 thoughts on “Getting a file from classpath

  1. Thanks Kamlesh. This is really helpful specially the last line to handle space.One more way to read file from class path is:

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s