Logo Questions Linux Laravel Mysql Ubuntu Git Menu

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();


ClassLoader classLoader = Config.class.getClassLoader();

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

How to access exactly resources folder?

like image 600
WildDev Avatar asked Mar 16 '23 20:03


1 Answers

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();
like image 192
Christian Hujer Avatar answered Mar 22 '23 09:03

Christian Hujer