Wednesday, May 13, 2009

Getting Class real path in Java

Getting web application real path is pretty straight forward:
getServletContext().getRealPath("/")
This code returns the physical root directory of a web application. Of course the method getServletContext() exists only in classes extending HttpServlet class. That mean, this method is available only for Servlets.
Sometimes it is useful to get the real path of a class. Something quite similar to the code shown above, but for a class and not for a Servlet. This is simple as well, but a bit less obvious:
AnyClass.class.getResource("/")
The function getResource with the parameter “/” returns a URL class containing the root directory in which the class resides.

Getting the full directory of the class can be done by simply passing empty string as a parameter:

AnyClass.class.getResource("")

For example, this code:

package com.bashan.blog.clazz;
public class AnyClass {
  public static void main(String[] args)
  {
    System.out.println(AnyClass.class.getResource("/"));
    System.out.println(AnyClass.class.getResource(""));
  }
}

Prints this output:

file:/C:/Users/bashan/IdeaProjects/out/production/general/
file:/C:/Users/bashan/IdeaProjects/out/production/general/com/bashan/blog/clazz/

So, what will happen if we try to use getResource() function on a class located in a jar file?

  • For the call getResource(“/”) we will still get the out class root directory.
  • For the call getResource(“”) we will get a URL containing our jar file and a full path to the location of the class in the jar. Note, that the protocol of the URL is “jar”.

For example for the following code:

package com.bashan.blog.clazz;
import org.json.simple.JSONArray;
import java.net.URL;
public class AnyClass {
  public static void main(String[] args)
  {
    System.out.println(JSONArray.class.getResource("/"));
    System.out.println(JSONArray.class.getResource(""));
    URL url = JSONArray.class.getResource("");
    System.out.println(url.getProtocol());
  }
}

We will get the following output:

file:/C:/Users/bashan/IdeaProjects/out/production/general/
jar:file:/C:/Users/bashan/IdeaProjects/general/lib/json_simple-1.1.jar!/org/json/simple/
jar

And finally, if we try the getResource() on Java standard classes like String:

package com.bashan.blog.clazz;
public class AnyClass {
  public static void main(String[] args)
  {
    System.out.println(String.class.getResource("/"));
    System.out.println(String.class.getResource(""));
  }
}

We will get:

file:/C:/Users/bashan/IdeaProjects/out/production/general/
null
Again, for the parameter “/” we get the class path of our code. And for the empty parameter we get “null”.

1 comment: