简体   繁体   中英

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM