Search code examples
javagradleresourcesclasspathclassloader

Can't access resources folder in Java


I tried to access resources (marked as) folder in Java app but nothing works, returns wrong paths

I've tried:

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
System.out.println(classLoader.getResource("."));

and

ClassLoader classLoader = Config.class.getClassLoader();
System.out.println(classLoader.getResource("."));

but it shows me file:/D:/testProject/build/classes/main/, and of course there's no resource files :(

How to access exactly resources folder?

-TestProject
 |-resources
 |-src
   |-main

Solution

  • Be aware that the word resource in your Gradle structure and the word resource in ClassLoader are unrelated.

    As your ClassLoader might have more than one root, you need to loop over the roots. Use getResources() instead of getResource(). See http://docs.oracle.com/javase/8/docs/api/java/lang/ClassLoader.html#getResources-java.lang.String-

    Like this:

    ClassLoader classLoader = Config.class.getClassLoader();
    // or use:
    // ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
    // depending on what's appropriate in your case.
    Enumeration<URL> roots = classLoader.getResources(".");
    while (roots.hasMoreElements()) {
        final URL url = roots.nextElement();
        System.out.println(url);
    }