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.