[英]Can't access resources folder in Java
I tried to access resources (marked as) folder in Java app but nothing works, returns wrong paths 我试图访问Java应用程序中的资源(标记为)文件夹,但没有任何作用,返回错误的路径
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 :( 但它显示我file:/D:/testProject/build/classes/main/
,当然没有资源文件:(
How to access exactly resources
folder? 如何准确访问resources
文件夹?
-TestProject
|-resources
|-src
|-main
Be aware that the word resource in your Gradle structure and the word resource in ClassLoader
are unrelated. 要知道,在你的摇篮结构的字资源 ,并在字资源 ClassLoader
是无关的。
As your ClassLoader
might have more than one root, you need to loop over the roots. 由于您的ClassLoader
可能有多个根,因此您需要遍历根。 Use getResources()
instead of getResource()
. 使用getResources()
而不是getResource()
。 See http://docs.oracle.com/javase/8/docs/api/java/lang/ClassLoader.html#getResources-java.lang.String- 请参阅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);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.