Loading resources from the classpath

Configuration files, templates and test data are usually shipped inside the application, on the classpath, not at a fixed place on disk. Java finds them through class loaders with getResource and getResourceAsStream. This page explains how the lookup works, why it so often returns null, what happens when two JARs contain the same file, and how to list a resource folder that lives inside a JAR.

Contents

How resource lookup works

A resource is any file that sits on the classpath next to the compiled classes: in a classpath directory or inside a JAR. In Maven and Gradle projects, files in src/main/resources end up there. A resource is identified by a name with / separators, such as config/app.properties, never by a disk path, because in production it is usually an entry inside a JAR and there is no file at all.

Class loaders find resources the same way they find classes. Since Java 9 there are three built-in loaders in a chain: the application loader (your classpath), its parent the platform loader (some JDK modules such as java.sql), and the bootstrap loader (the core of the JDK, shown as null). A lookup asks the parent first and then searches its own classpath entries in order, so the first match wins. The result is a URL: file: for a directory entry, jar: for a JAR entry and jrt: for the JDK's own runtime image.

The resource lookup methods
MethodSinceReturnsName is relative to
Class.getResource, getResourceAsStreamJava 1.1URL or stream, null if missingThe class's package, unless it starts with /
ClassLoader.getResource, getResourceAsStreamJava 1.1URL or stream, null if missingThe classpath root; no leading /
ClassLoader.getResourcesJava 1.2Every match, as an EnumerationThe classpath root
ClassLoader.resourcesJava 9Every match, as a StreamThe classpath root
ClassLoader.getSystemResourceJava 1.1URL from the application loaderThe classpath root
Module.getResourceAsStreamJava 9Stream from one moduleThe module root

The programs on this page run with this classpath:

Output
res/config/app.properties        (app.name, app.port and a feature flag)
res/config/logging.properties    (a second file in the same folder)
res/com/demo/defaults.txt        (next to the package com.demo)
data.jar!/data/cities.txt        (inside a JAR)
data.jar!/data/countries.txt
data.jar!/config/app.properties  (a second copy, with other values)

The run command is java -cp out:res:data.jar ResourceLookup, where out holds the compiled classes; the order matters, as the duplicates section shows. One helper class lives in package com.demo so that package-relative lookups can be shown. All programs were compiled and run on JDK 21.

Java
package com.demo;

import java.net.URL;

// A class in package com.demo, used to show package-relative lookups
public final class Loader {
    private Loader() {
    }

    public static URL relative(String name) {
        return Loader.class.getResource(name);
    }
}

Class.getResource versus ClassLoader.getResource

The two lookups interpret names differently. The program asks both for the same names, with and without a leading slash, and prints where each one points, or null.

Java
import com.demo.Loader;
import java.net.URL;

public class ResourceLookup {

    static String where(URL url) {
        if (url == null) {
            return "null (not found)";
        }
        String s = url.toString();
        // Shorten the machine-specific part of the location
        return url.getProtocol() + ": ..." + s.substring(s.indexOf("classpath-resources/") + 19);
    }

    static void show(String label, URL url) {
        System.out.printf("%-40s -> %s%n", label, where(url));
    }

    public static void main(String[] args) {
        ClassLoader cl = ResourceLookup.class.getClassLoader();

        // Class.getResource: relative to the class's package unless it starts with /
        show("Loader.class, \"defaults.txt\"", Loader.relative("defaults.txt"));
        show("Loader.class, \"/config/app.properties\"", Loader.relative("/config/app.properties"));
        show("Loader.class, \"config/app.properties\"", Loader.relative("config/app.properties"));

        // ClassLoader.getResource: always from the root, and must NOT start with /
        show("ClassLoader, \"config/app.properties\"", cl.getResource("config/app.properties"));
        show("ClassLoader, \"/config/app.properties\"", cl.getResource("/config/app.properties"));

        // A resource inside a JAR has a jar: URL, not a file
        show("ClassLoader, \"data/cities.txt\"", cl.getResource("data/cities.txt"));
    }
}

Output (the machine-specific start of each location is shortened to ...):

Output
Loader.class, "defaults.txt"             -> file: .../res/com/demo/defaults.txt
Loader.class, "/config/app.properties"   -> file: .../res/config/app.properties
Loader.class, "config/app.properties"    -> null (not found)
ClassLoader, "config/app.properties"     -> file: .../res/config/app.properties
ClassLoader, "/config/app.properties"    -> null (not found)
ClassLoader, "data/cities.txt"           -> jar: .../data.jar!/data/cities.txt
How resource names are resolved
CallName without /Name with leading /
SomeClass.class.getResource(name)Relative to the class's package: com/demo/defaults.txtFrom the classpath root
classLoader.getResource(name)From the classpath rootNot found: returns null

Two of the six lookups returned null, both for a file that exists. Loader.class looked for com/demo/config/app.properties, because a name without a slash is relative to its package. The class loader does not strip a leading slash, so /config/app.properties matches nothing. A null resource is almost always one of these two mistakes. Class.getResource is in fact a thin wrapper: it turns the name into an absolute one and then asks the class's loader. The last line shows that a resource inside a JAR is addressed with a jar: URL that names the JAR, then !, then the entry.

Reading resources

getResourceAsStream opens the resource directly, whether it is a file or a JAR entry. The program reads the properties file as text and as Properties, reads the JAR entry line by line, and then tries two things that fail.

Java
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.StandardCharsets;
import java.nio.file.FileSystemNotFoundException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.List;
import java.util.Objects;
import java.util.Properties;

public class ReadResources {

    static InputStream open(String name) {
        InputStream in = ReadResources.class.getClassLoader().getResourceAsStream(name);
        return Objects.requireNonNull(in, () -> "resource not found: " + name);
    }

    public static void main(String[] args) throws Exception {
        // As a String
        try (InputStream in = open("config/app.properties")) {
            String text = new String(in.readAllBytes(), StandardCharsets.UTF_8);
            System.out.println("as text: " + text.lines().count() + " lines");
        }

        // As Properties
        Properties props = new Properties();
        try (InputStream in = open("config/app.properties")) {
            props.load(in);
        }
        System.out.println("as Properties: name=" + props.getProperty("app.name") + ", port="
                + Integer.parseInt(props.getProperty("app.port")));

        // Line by line, from inside the JAR
        try (BufferedReader r = new BufferedReader(new InputStreamReader(open("data/cities.txt"),
                StandardCharsets.UTF_8))) {
            List<String> cities = r.lines().toList();
            System.out.println("from the JAR: " + cities);
        }

        // A missing resource gives null, which requireNonNull turns into a clear message
        try {
            open("config/missing.yaml");
        } catch (NullPointerException e) {
            System.out.println("missing: " + e.getMessage());
        }

        // Treating a JAR resource as a file fails: there is no file on disk
        try {
            Path p = Paths.get(ReadResources.class.getClassLoader()
                    .getResource("data/cities.txt").toURI());
            Files.readAllLines(p);
        } catch (FileSystemNotFoundException e) {
            System.out.println("Paths.get on a jar: URL -> FileSystemNotFoundException");
        }
    }
}

Output:

Output
as text: 4 lines
as Properties: name=Demo Shop, port=8080
from the JAR: [Oslo, Lima, Rome]
missing: resource not found: config/missing.yaml
Paths.get on a jar: URL -> FileSystemNotFoundException
  • readAllBytes (Java 9) reads a small resource in one call. The properties file has four lines including the comment.
  • Properties.load takes the stream directly. Values are strings, so the port is parsed with Integer.parseInt. See properties files for the format and its encoding rules.
  • For text, wrap the stream in an InputStreamReader with an explicit charset, then in a BufferedReader; see reading a text file for why the charset matters.
  • getResourceAsStream returns null for a missing resource instead of throwing. Checking it with Objects.requireNonNull and a message turns a confusing NullPointerException later into a clear error at the right place.
  • Converting a resource URL to a Path works in the IDE, where resources are plain files, and fails in production, where they are inside a JAR. Here Paths.get(uri) threw FileSystemNotFoundException. Read resources through streams; the listing section shows the one case where a Path is useful.

Duplicate resources and classpath order

Nothing stops two classpath entries from containing the same resource name. Here both res and data.jar contain config/app.properties, with different values, which is what happens when a library ships its own defaults under a common name.

Java
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.Collections;
import java.util.List;
import java.util.Properties;

public class Shadowing {

    static String shortName(URL url) {
        String s = url.toString();
        return s.substring(s.indexOf("classpath-resources/") + 20);
    }

    public static void main(String[] args) throws IOException {
        ClassLoader cl = Shadowing.class.getClassLoader();
        String name = "config/app.properties";

        // getResources lists every match, in classpath order
        List<URL> all = Collections.list(cl.getResources(name));
        System.out.println(all.size() + " copies of " + name + " on the classpath:");
        for (URL url : all) {
            Properties p = new Properties();
            try (InputStream in = url.openStream()) {
                p.load(in);
            }
            System.out.println("  " + shortName(url) + "  app.name=" + p.getProperty("app.name"));
        }

        // getResource returns only the first one
        System.out.println("getResource picks: " + shortName(cl.getResource(name)));

        // The Java 9 stream form
        System.out.println("resources(name).count(): " + cl.resources(name).count());

        // A merge that lets later copies fill in keys the first one lacks
        Properties merged = new Properties();
        for (int i = all.size() - 1; i >= 0; i--) {
            try (InputStream in = all.get(i).openStream()) {
                merged.load(in);                            // earlier copies overwrite later
            }
        }
        System.out.println("merged: app.name=" + merged.getProperty("app.name")
                + ", app.timeout=" + merged.getProperty("app.timeout")
                + ", keys=" + merged.size());
    }
}

Output:

Output
2 copies of config/app.properties on the classpath:
  res/config/app.properties  app.name=Demo Shop
  data.jar!/config/app.properties  app.name=Jar Default
getResource picks: res/config/app.properties
resources(name).count(): 2
merged: app.name=Demo Shop, app.timeout=30, keys=4
  • getResources found both copies, in classpath order: res before data.jar, because that is their order in -cp.
  • getResource returned only the first, so the JAR's "Jar Default" is invisible to normal code. Swapping the classpath order would silently change which configuration the application reads. Build tools fix the order, but two libraries with the same resource name can still collide.
  • Loading the copies from last to first into one Properties merged them: the first copy's app.name won, and app.timeout=30, which only the JAR's copy has, filled the gap. ServiceLoader uses getResources in the same way to find every META-INF/services file; see ServiceLoader.

Which class loader: null loaders and the context loader

Every class has a loader, and the loader decides what the class can see. The program prints the loader chain and shows the two places where that bites: JDK classes, whose loader can be null, and frameworks, which look up resources through the thread's context class loader.

Java
import java.net.URL;

public class LoaderTrees {

    static String describe(ClassLoader cl) {
        return cl == null ? "null (the bootstrap loader)" : cl.getName() + " ("
                + cl.getClass().getSimpleName() + ")";
    }

    public static void main(String[] args) {
        // The loader chain: application -> platform -> bootstrap
        ClassLoader app = LoaderTrees.class.getClassLoader();
        System.out.println("this class:    " + describe(app));
        System.out.println("its parent:    " + describe(app.getParent()));
        System.out.println("grandparent:   " + describe(app.getParent().getParent()));
        System.out.println("java.sql.Date: " + describe(java.sql.Date.class.getClassLoader()));
        System.out.println("String:        " + describe(String.class.getClassLoader()));

        // JDK classes are resources too, served from the runtime image
        URL objectClass = Object.class.getResource("Object.class");
        System.out.println("Object.class resource: " + objectClass);

        // The trap: String's loader is null, so this throws
        try {
            String.class.getClassLoader().getResource("config/app.properties");
        } catch (NullPointerException e) {
            System.out.println("String.class.getClassLoader().getResource: NullPointerException");
        }
        // Class.getResource handles the null loader by asking the system class loader
        System.out.println("ClassLoader.getSystemResource finds it: "
                + (ClassLoader.getSystemResource("config/app.properties") != null));

        // The thread context class loader: what frameworks use
        ClassLoader context = Thread.currentThread().getContextClassLoader();
        System.out.println("context loader is the application loader: " + (context == app));
    }
}

Output:

Output
this class:    app (AppClassLoader)
its parent:    platform (PlatformClassLoader)
grandparent:   null (the bootstrap loader)
java.sql.Date: platform (PlatformClassLoader)
String:        null (the bootstrap loader)
Object.class resource: jrt:/java.base/java/lang/Object.class
String.class.getClassLoader().getResource: NullPointerException
ClassLoader.getSystemResource finds it: true
context loader is the application loader: true
  • The chain is application, platform, then bootstrap. java.sql.Date comes from the platform loader, and String from the bootstrap loader, which Java represents as null.
  • JDK classes are resources too. Object.class has a jrt:/java.base/... URL: since Java 9 the JDK is stored in a runtime image instead of rt.jar.
  • String.class.getClassLoader().getResource(...) threw NullPointerException, because the loader is null. Library code that writes someClass.getClassLoader() must handle that, or use ClassLoader.getSystemResource, which found the file.
  • Thread.getContextClassLoader() is a loader attached to the thread. In a plain program it is the application loader. Application servers and plugin systems set it to the loader of the current application, so a library loaded by a parent loader can still find the application's resources. That is why many frameworks look up resources through it rather than through their own class.

Listing a resource folder, on disk or inside a JAR

There is no class loader method that lists resources. For a folder you know, the URL tells you where it is, and the right file system can list it: the default one for file: URLs, the ZIP file system for jar: URLs. The program lists config/, which is a directory in res, and data/, which is inside the JAR, and then reads a JAR entry as a Path.

Java
import java.net.URI;
import java.net.URL;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.Map;
import java.util.stream.Stream;

public class ListResources {

    // Lists the entries of a resource directory, whether it is on disk or inside a JAR
    static void list(String dir) throws Exception {
        URL url = ListResources.class.getClassLoader().getResource(dir);
        URI uri = url.toURI();
        System.out.println(dir + " -> " + uri.getScheme() + ":");
        if (uri.getScheme().equals("jar")) {
            try (FileSystem jar = FileSystems.newFileSystem(uri, Map.of());
                 Stream<Path> s = Files.list(jar.getPath(dir))) {
                s.map(p -> p.getFileName().toString()).sorted()
                        .forEach(n -> System.out.println("  " + n));
            }
        } else {
            try (Stream<Path> s = Files.list(Path.of(uri))) {
                s.map(p -> p.getFileName().toString()).sorted()
                        .forEach(n -> System.out.println("  " + n));
            }
        }
    }

    public static void main(String[] args) throws Exception {
        list("config/");                        // a directory in res/
        list("data/");                          // a directory inside data.jar

        // Reading a JAR entry through the ZIP file system, as a Path
        URI cities = ListResources.class.getClassLoader().getResource("data/cities.txt").toURI();
        try (FileSystem jar = FileSystems.newFileSystem(cities, Map.of())) {
            Path p = jar.provider().getPath(cities);
            System.out.println("as a Path inside the JAR: " + Files.readAllLines(p));
        }
    }
}

Output:

Output
config/ -> file:
  app.properties
  logging.properties
data/ -> jar:
  cities.txt
  countries.txt
as a Path inside the JAR: [Oslo, Lima, Rome]
  • config/ resolved to a file: URL, so Path.of(uri) and Files.list worked directly and found both properties files.
  • data/ resolved to a jar: URL. FileSystems.newFileSystem(uri, Map.of()) opened the JAR as a file system, after which Files.list worked the same way. This is the fix for the FileSystemNotFoundException above. Close the file system when done.
  • Only the first matching folder is listed: if two JARs both had data/, you would need getResources("data/") and a listing of each.
  • Folder lookups depend on the JAR having directory entries. The jar tool writes them, but a JAR built without them returns null for getResource("data/") even though data/cities.txt is found. When you control the format, ship an index file that names the resources instead of listing folders.

Tests and modules

Build tools put test resources (src/test/resources) on the test classpath ahead of the main ones, so a test can supply its own config/app.properties that shadows the production file of the same name, exactly as res shadowed the JAR above.

In a named module, resources in a package are encapsulated like classes: other modules can read them only if the package is opensed. Resources at the module root, or in directories whose names are not valid package names (such as META-INF), are not restricted, and neither are .class files. Code in the module can always read its own resources with getClass().getResourceAsStream. See the module system.

Which method to use

Choosing a resource lookup
NeedUse
A resource next to your classMyClass.class.getResourceAsStream("file.txt")
A resource by its full nameMyClass.class.getResourceAsStream("/config/app.properties") or the class loader without the slash
Fail clearly when it is missingWrap the stream in Objects.requireNonNull with a message
Read textInputStreamReader with an explicit charset
Every copy on the classpathgetResources or resources
Library code used inside application serversThread.currentThread().getContextClassLoader()
List files in a resource folderUse the URL's file system: Path.of for file:, FileSystems.newFileSystem for jar:
A file the user editsNot a resource: a real path, for example from a system property

For more on JAR files and the ZIP file system, see ZIP and GZIP; for how class loaders work in general, see class loading.