June 11, 2008
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.
Tags: application, class, File, getresourceasstream, GWT, java file, java url, language java, shell, source language
Thanks a lot! Exactly what I was looking for.
Comment by Patrick — August 24, 2011 @ 11:48