How to get absolute path to file in /resources folder of your project

James Raitsev picture James Raitsev · Jun 27, 2013 · Viewed 251.5k times · Source

Assume standard maven setup.

Say in your resources folder you have a file abc.

In Java, how can I get absolute path to the file please?

Answer

Karol S picture Karol S · Feb 6, 2014

The proper way that actually works:

URL resource = YourClass.class.getResource("abc");
Paths.get(resource.toURI()).toFile();

It doesn't matter now where the file in the classpath physically is, it will be found as long as the resource is actually a file and not a JAR entry.

(The seemingly obvious new File(resource.getPath()) doesn't work for all paths! The path is still URL-encoded!)