Finding the Directory Where Your Java .class File is Loaded From
Today I had to solve an unusual problem: I needed to find the directory that was used to load a specific Java .class file (the location in the file system of given .class file). I needed it because I wanted to load resources located somewhere in the classPath with file access API (not with accessable as streams). I needed something like getClass().getResourceAsStream() but for a directory.
The first idea I had was to use the following code:
URL url = getClass().getResource(".");
This works well in a console application but in a servlet container (e.g. in Tomcat or in GWT shell) it runs differently.
Later I found on the net a really nice solution:
URL classesRootDir = getClass().getProtectionDomain().getCodeSource().getLocation();
The above returns the base directory used when loading your .class files. It does not contain the package. It contains the classpath directory only. For example, in a console application the above returns someting like this:
In a Web application it returns someting like this:
It also works well for GWT applications running in hosted mode in GWT shell and in a compiled mode in JBoss. This was the real solution.
5 Responses to “Finding the Directory Where Your Java .class File is Loaded From”
Thanks a lot! Exactly what I was looking for.
But, as soon as your class is deployed through a jar, war or EAR, the above does not work. getProtectionDomain().getCodeSource().getLocation().getFile() would then return the path to the embedding package as running on the runtime.
Stackoverflow has many threads about the same problem.
Perfect. Just what I needed. Thanks for posting this.
Note that the classes which implement the Java 2 SDK tools are in a separate archive from the bootstrap classes. The tools archive is the SDK’s