This one works for me:

return Path.of(ClassLoader.getSystemResource(resourceName).toURI());
Answer from keyoxy on Stack Overflow
🌐
Oracle
docs.oracle.com › javase › 8 › docs › technotes › guides › lang › resources.html
Location-Independent Access to Resources
April 21, 2026 - The ClassLoader methods search each directory, ZIP file, or JAR file entry in the CLASSPATH for the resource file, and, if found, returns either an InputStream, or the resource name. If not found, the methods return null. A resource may be found in a different entry in the CLASSPATH than the location where the class file was loaded. The implementation of getResource on a class loader depends on the details of the ClassLoader class.
🌐
Baeldung
baeldung.com › home › java › java io › get a path to a resource in a java jar file
Get a Path to a Resource in a Java JAR File | Baeldung
February 8, 2025 - This means it can locate resources ... package. Starting from Java 7, we can use the Paths.get() method to obtain a Path object representing a resource within a JAR file....
🌐
Baeldung
baeldung.com › home › spring › access a file from the classpath in a spring application
Access a File from the Classpath using Spring | Baeldung
March 26, 2025 - ApplicationContext context; public Resource loadEmployeesWithApplicationContext() { return context.getResource("classpath:data/employees.dat"); } As a caveat, there is another way to retrieve resources in Spring, but the ResourceUtils Javadoc is clear that the class is mainly for internal use.
🌐
GeeksforGeeks
geeksforgeeks.org › java › loading-resources-from-classpath-in-java-with-example
Loading Resources from Classpath in Java with Example - GeeksforGeeks
July 23, 2025 - So basically two methods named: getResource() and getResourceAsStream() are used to load the resources from the classpath. These methods generally return the URL's and input streams respectively.
🌐
Spring
docs.spring.io › spring-framework › docs › current › javadoc-api › org › springframework › core › io › ClassPathResource.html
ClassPathResource (Spring Framework 7.0.7 API)
This implementation returns a URL for the underlying class path resource, if available. ... IOException - if the resource cannot be resolved as URL, i.e. if the resource is not available as a descriptor ... This implementation creates a ClassPathResource, applying the given path relative to the path used to create this descriptor.
🌐
Bryanbende
bryanbende.com › development › 2014 › 10 › 20 › extracting-classpath-resources
Extracting Classpath Resources
October 20, 2014 - public static Collection<String> getResources(final Pattern pattern){ final ArrayList<String> retval = new ArrayList<String>(); final String classPath = System.getProperty("java.class.path", "."); final String[] classPathElements = classPath.split( File.pathSeparator); for(final String element : classPathElements){ retval.addAll(getResources(element, pattern)); } return retval; }
🌐
Spring
docs.spring.io › spring-framework › docs › 3.0.6.RELEASE_to_3.1.0.BUILD-SNAPSHOT › 3.0.6.RELEASE › org › springframework › core › io › ClassPathResource.html
ClassPathResource
Create a new ClassPathResource with optional ClassLoader and Class. Only for internal usage. ... Return the path for this resource (as resource path within the class path). public final java.lang.ClassLoader getClassLoader()
Top answer
1 of 16
202

Custom Scanner

Implement your own scanner. For example:

(limitations of this solution are mentioned in the comments)

private List<String> getResourceFiles(String path) throws IOException {
    List<String> filenames = new ArrayList<>();

    try (
            InputStream in = getResourceAsStream(path);
            BufferedReader br = new BufferedReader(new InputStreamReader(in))) {
        String resource;

        while ((resource = br.readLine()) != null) {
            filenames.add(resource);
        }
    }

    return filenames;
}

private InputStream getResourceAsStream(String resource) {
    final InputStream in
            = getContextClassLoader().getResourceAsStream(resource);

    return in == null ? getClass().getResourceAsStream(resource) : in;
}

private ClassLoader getContextClassLoader() {
    return Thread.currentThread().getContextClassLoader();
}

Spring Framework

Use PathMatchingResourcePatternResolver from Spring Framework.

Ronmamo Reflections

The other techniques might be slow at runtime for huge CLASSPATH values. A faster solution is to use ronmamo's Reflections API, which precompiles the search at compile time.

2 of 16
69

Here is the code
Source: forums.devx.com/showthread.php?t=153784

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;

/**
 * list resources available from the classpath @ *
 */
public class ResourceList{

    /**
     * for all elements of java.class.path get a Collection of resources Pattern
     * pattern = Pattern.compile(".*"); gets all resources
     * 
     * @param pattern
     *            the pattern to match
     * @return the resources in the order they are found
     */
    public static Collection<String> getResources(
        final Pattern pattern){
        final ArrayList<String> retval = new ArrayList<String>();
        final String classPath = System.getProperty("java.class.path", ".");
        final String[] classPathElements = classPath.split(System.getProperty("path.separator"));
        for(final String element : classPathElements){
            retval.addAll(getResources(element, pattern));
        }
        return retval;
    }

    private static Collection<String> getResources(
        final String element,
        final Pattern pattern){
        final ArrayList<String> retval = new ArrayList<String>();
        final File file = new File(element);
        if(file.isDirectory()){
            retval.addAll(getResourcesFromDirectory(file, pattern));
        } else{
            retval.addAll(getResourcesFromJarFile(file, pattern));
        }
        return retval;
    }

    private static Collection<String> getResourcesFromJarFile(
        final File file,
        final Pattern pattern){
        final ArrayList<String> retval = new ArrayList<String>();
        ZipFile zf;
        try{
            zf = new ZipFile(file);
        } catch(final ZipException e){
            throw new Error(e);
        } catch(final IOException e){
            throw new Error(e);
        }
        final Enumeration e = zf.entries();
        while(e.hasMoreElements()){
            final ZipEntry ze = (ZipEntry) e.nextElement();
            final String fileName = ze.getName();
            final boolean accept = pattern.matcher(fileName).matches();
            if(accept){
                retval.add(fileName);
            }
        }
        try{
            zf.close();
        } catch(final IOException e1){
            throw new Error(e1);
        }
        return retval;
    }

    private static Collection<String> getResourcesFromDirectory(
        final File directory,
        final Pattern pattern){
        final ArrayList<String> retval = new ArrayList<String>();
        final File[] fileList = directory.listFiles();
        for(final File file : fileList){
            if(file.isDirectory()){
                retval.addAll(getResourcesFromDirectory(file, pattern));
            } else{
                try{
                    final String fileName = file.getCanonicalPath();
                    final boolean accept = pattern.matcher(fileName).matches();
                    if(accept){
                        retval.add(fileName);
                    }
                } catch(final IOException e){
                    throw new Error(e);
                }
            }
        }
        return retval;
    }

    /**
     * list the resources that match args[0]
     * 
     * @param args
     *            args[0] is the pattern to match, or list all resources if
     *            there are no args
     */
    public static void main(final String[] args){
        Pattern pattern;
        if(args.length < 1){
            pattern = Pattern.compile(".*");
        } else{
            pattern = Pattern.compile(args[0]);
        }
        final Collection<String> list = ResourceList.getResources(pattern);
        for(final String name : list){
            System.out.println(name);
        }
    }
}  

If you are using Spring Have a look at PathMatchingResourcePatternResolver

Find elsewhere
🌐
Spring
docs.spring.io › spring-framework › docs › 3.2.x › spring-framework-reference › html › resources.html
6. Resources
If the specified path is already ... a classpath location, then the resolver must obtain the last non-wildcard path segment URL via a Classloader.getResource() call....
🌐
Blogger
javarevisited.blogspot.com › 2014 › 07 › how-to-load-resources-from-classpath-in-java-example.html
How to Load Resources from Classpath in Java with Example
If you look closely you will find that we have used both getResource() and getResourceAsStream() methods to load resources from classpath in Java, in this case just properties file.
🌐
Medium
medium.com › @AlexanderObregon › simplifying-resource-handling-with-value-and-classpathresource-in-spring-ad7dd63d4ebf
Using @Value and ClassPathResource for Easier Resource Handling in Spring
March 27, 2025 - This is easily done by creating an instance of the class, passing the path of the resource as a parameter, and then using its getInputStream() method to read the file: ClassPathResource resource = new ClassPathResource("config/application.p...
🌐
Mkyong
mkyong.com › home › java › java – read a file from resources folder
Java - Read a file from resources folder - Mkyong.com
September 4, 2020 - In Java, we can use getResourceAsStream or getResource to read a file or multiple files from a resources folder or root of the classpath.
🌐
Xenovation
xenovation.com › home › blog › java › java - read file from classpath
Java - Read file from classpath | XENOVATION
April 24, 2019 - ProjectName > Properties > Java Build Path > Source tab · Now we can read resource file in Java. Lets say that we have created Java project called ClasspathExample and we need to read example.xml from it, firstly we need to add resource folder to classpath and then read it. package com.xenovation; import java.io.File; import java.net.URL; public class ClasspathExample { public File readFileFromClasspath() { URL fileUrl = getClass().getResource("/example.xml"); return new File(fileUrl.getFile()); } } Here we used getClass().getResource(), this method is trying to read our file example.xml from the root "/" path of the classpath.
🌐
Baeldung
baeldung.com › home › testing › get the path of the /src/test/resources directory in junit
Get the Path of the /src/test/resources Directory in JUnit | Baeldung
February 20, 2026 - The simplest approach uses an instance of the java.io.File class to read the /src/test/resources directory by calling the getAbsolutePath() method: String path = "src/test/resources"; File file = new File(path); String absolutePath = ...
🌐
LogicBig
logicbig.com › how-to › java › different-ways-to-load-resources.html
What are different ways to load classpath resources in Java?
November 4, 2018 - [INFO] [INFO] ------------------------------------------------------------------------ [INFO] Building load-resource 1.0-SNAPSHOT [INFO] ------------------------------------------------------------------------ [INFO] [INFO] --- exec-maven-plugin:1.4.0:java (default-cli) @ load-resource --- ----------------------------------------- using this.getClass().getResource ----------------------------------------- -> attempting input resource: test-pkg-resource.txt no resource found: test-pkg-resource.txt -> attempting input resource: /test-pkg-resource.txt absolute resource path found : C:/load-resour
🌐
TutorialsPoint
tutorialspoint.com › loading-resources-from-classpath-in-java-with-example
Loading Resources from classpath in Java with Example
July 28, 2023 - Be mindful that when providing a path argument for this approach it must be relative in orientation to your classpaths' root - much like with utilizing getResourceAsStream(). In summary, there exist diverse methods of loading resources from classpath in Java-such as utilizing ClassLoader.getResource() or ClassLoader.getResourceAsStream().
🌐
Spring
docs.spring.io › spring-framework › docs › 5.0.0.M4_to_5.0.0.M5 › Spring Framework 5.0.0.M5 › org › springframework › core › io › ClassPathResource.html
ClassPathResource - Spring
Create a new ClassPathResource with optional ClassLoader and Class. Only for internal usage. ... Return the path for this resource (as resource path within the class path). public final java.lang.ClassLoader getClassLoader()
🌐
Spring
docs.spring.io › spring-framework › docs › 2.5.x › reference › resources.html
Chapter 4. Resources
If the specified path is already ... a classpath location, then the resolver must obtain the last non-wildcard path segment URL via a Classloader.getResource() call....