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/config/app.properties
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.sqlnullURLfile:jar:jrt:
| Method | Since | Returns | Name is relative to |
|---|---|---|---|
Class.getResourcegetResourceAsStream | Java 1.1 | URL or stream, null | The class's package, unless it starts with / |
ClassLoader.getResourcegetResourceAsStream | Java 1.1 | URL or stream, null | The classpath root; no leading / |
ClassLoader.getResources | Java 1.2 | Every match, as an Enumeration | The classpath root |
ClassLoader.resources | Java 9 | Every match, as a Stream | The classpath root |
ClassLoader.getSystemResource | Java 1.1 | URL from the application loader | The classpath root |
Module.getResourceAsStream | Java 9 | Stream from one module | The module root |
The programs on this page run with this classpath:
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 ResourceLookupoutcom.demo
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
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 ...
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
| Call | Name without / | Name with leading / |
|---|---|---|
SomeClass.class.getResource(name) | Relative to the class's package: com/demo/defaults.txt | From the classpath root |
classLoader.getResource(name) | From the classpath root | Not found: returns null |
Two of the six lookups returned nullLoader.classcom/demo/config/app.properties/config/app.propertiesnullClass.getResourcejar:!
Reading resources
getResourceAsStreamProperties
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:
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
(Java 9) reads a small resource in one call. The properties file has four lines including the comment.readAllBytes takes the stream directly. Values are strings, so the port is parsed withProperties.load . SeeInteger.parseIntproperties files for the format and its encoding rules.- For text, wrap the stream in an
with an explicit charset, then in aInputStreamReader ; seeBufferedReaderreading a text file for why the charset matters. returnsgetResourceAsStream for a missing resource instead of throwing. Checking it withnull and a message turns a confusingObjects.requireNonNull later into a clear error at the right place.NullPointerException- Converting a resource URL to a
works in the IDE, where resources are plain files, and fails in production, where they are inside a JAR. HerePath threwPaths.get(uri) . Read resources through streams; the listing section shows the one case where aFileSystemNotFoundException is useful.Path
Duplicate resources and classpath order
Nothing stops two classpath entries from containing the same resource name. Here both resdata.jarconfig/app.properties
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:
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
found both copies, in classpath order:getResources beforeres , because that is their order indata.jar .-cp 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.getResource- Loading the copies from last to first into one
merged them: the first copy'sProperties won, andapp.name , which only the JAR's copy has, filled the gap.app.timeout=30 usesServiceLoader in the same way to find everygetResources file; seeMETA-INF/servicesServiceLoader .
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
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:
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.
comes from the platform loader, andjava.sql.Date from the bootstrap loader, which Java represents asString .null - JDK classes are resources too.
has aObject.class URL: since Java 9 the JDK is stored in a runtime image instead ofjrt:/java.base/... .rt.jar threwString.class.getClassLoader().getResource(...) , because the loader isNullPointerException . Library code that writesnull must handle that, or usesomeClass.getClassLoader() , which found the file.ClassLoader.getSystemResource 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.Thread.getContextClassLoader()
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:jar:config/resdata/Path
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:
config/ -> file:
app.properties
logging.properties
data/ -> jar:
cities.txt
countries.txt
as a Path inside the JAR: [Oslo, Lima, Rome]
resolved to aconfig/ URL, sofile: andPath.of(uri) worked directly and found both properties files.Files.list resolved to adata/ URL.jar: opened the JAR as a file system, after whichFileSystems.newFileSystem(uri, Map.of()) worked the same way. This is the fix for theFiles.list above. Close the file system when done.FileSystemNotFoundException- Only the first matching folder is listed: if two JARs both had
, you would needdata/ and a listing of each.getResources("data/") - Folder lookups depend on the JAR having directory entries. The
tool writes them, but a JAR built without them returnsjar fornull even thoughgetResource("data/") is found. When you control the format, ship an index file that names the resources instead of listing folders.data/cities.txt
Tests and modules
Build tools put test resources (src/test/resourcesconfig/app.propertiesres
In a named module, resources in a package are encapsulated like classes: other modules can read them only if the package is opensMETA-INF.classgetClass().getResourceAsStream
Which method to use
| Need | Use |
|---|---|
| A resource next to your class | MyClass.class.getResourceAsStream("file.txt") |
| A resource by its full name | MyClass.class.getResourceAsStream("/config/app.properties") |
| Fail clearly when it is missing | Wrap the stream in Objects.requireNonNull |
| Read text | InputStreamReader |
| Every copy on the classpath | getResourcesresources |
| Library code used inside application servers | Thread.currentThread().getContextClassLoader() |
| List files in a resource folder | Use the URL's file system: Path.offile:FileSystems.newFileSystemjar: |
| A file the user edits | Not a resource: a real path, for example from a system property |
For more on JAR files and the ZIP file system, see