Menu

Nakov.com logo

Thoughts on Software Engineering

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:

file:/C:/Documents%20and%20Settings/Administrator/workspace/TestPrj/bin/

In a Web application it returns someting like this:

file:/C:/Tomcat/webapps/MyApp/WEB-INF/classes/

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.

Previews (8,048), Views (2,033), Comments (3)

3 Responses to “Finding the Directory Where Your Java .class File is Loaded From”

  1. Patrick says:

    Thanks a lot! Exactly what I was looking for.

  2. Satish says:

    Amazing!!

  3. Sylvain says:

    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.

RSS feed for comments on this post. TrackBack URL

LEAVE A COMMENT