How do I use the Java ClassLoader to load a file fromthe classpath?

拟墨画扇 提交于 2019-11-29 14:00:25

问题


I want to use the ClassLoader to load a properties file for the Properties class. I've simplified the below code to remove error handling for the purposes of this discussion:

loader = this.getClass().getClassLoader();
in = loader.getResourceAsStream("theta.properties");
result = new Properties();
result.load(in);

In the same directory as this class I have the file "theta.properties" but the InputStream is always null. Am I putting the file in the wrong place? I'm using eclipse and its set to build the class files to the source folder - so that shouldn't be the problem.

I can't find anything in the JavaDoc to get the ClassLoader to tell me what classpath is being searched.


回答1:


By using getClass().getClassloader() you look for "theta.properties" from the root path directory. Just use getClass().getResourceAsStream() to get a resource relative to that class.




回答2:


If the file is in the same directory as the class, you have to prefix the class's package as a directory.

So if your package is:

package com.foo.bar;

Then your code is:

.getResourceAsStream("com/foo/bar/theta.properties");



回答3:


You can use ResourceBundle



来源:https://stackoverflow.com/questions/1094786/how-do-i-use-the-java-classloader-to-load-a-file-fromthe-classpath

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!