Search code examples
javaclassloaderjava-7urlclassloader

Using files as resources with URLClassLoader


I'm trying to write a Java 1.7 application that can be passed an arbitrary file from the command line. That file will be added to a ClassLoader so that it may be utilised as a resource.

Adding the file to a URLClassLoader seems to work, but how can I get that file as a resource after adding to the ClassLoader?

import java.io.File;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.Arrays;

public class ClassLoaderTest {

  public static void main(String... args) throws MalformedURLException {

    File file = new File("/tmp/application.conf");
    URLClassLoader classLoader = new URLClassLoader(new URL[]{file.toURI().toURL()});
    System.out.println("ClassLoader URLs: " + Arrays.toString(classLoader.getURLs()));

    if (file.exists()) {
      System.out.println("File \"" + file.getAbsolutePath() + "\" exists!");
    } else {
      System.out.println("File \"" + file.getAbsolutePath() + "\" does not exist!");
      return;
    }

    URL url = classLoader.getResource(file.getAbsolutePath());

    System.out.println("File \"" + file.getAbsolutePath() + "\" as url: " + url);

    assert url != null;

  }
}

Solution

  • URLClassLoader supports only jar files and directories of files. So there are two options:

    1. Put your resources into a jar file and add that jar file into your URLClassLoader.
    2. Provide the directory to the class loader and use the relative path to the file from that directory.