Example code for Accessing Java Resources

Published: Sunday, 15 August 2004

Directory in CLASSPATH

If a file you want is in the CLASSPATH, and relative to a package, then you can get a File object that refers to the directory. e.g. in the following situation:

package com.magicmonster.test;

public class ResourceTest {
  public static void main (String args[]) {
    File f = new File(this.getClass().getResource("TestResourceDir").getFile());

Note that the argument to getResource is the String TestResourceDir. It is a relative path to the current class.