Example code for Accessing Java Resources

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.

  1. There is a directory called classpath_dir that is in the CLASSPATH.

  2. We have written code in a package called com.magicmonster.test, and within a class called ResourceTest.

  3. There exists a directory classpath_dir/com/magicmonster/test/TestResourceDir.


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.

Published: Sunday, 15 August 2004