如何使用Java ClassLoader从类路径加载文件? [英] How do I use the Java ClassLoader to load a file fromthe classpath?
问题描述
我想使用ClassLoader加载Properties类的属性文件。为了便于讨论,我简化了以下代码以删除错误处理:
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);
在与此类相同的目录中,我有文件theta.properties但是InputStream总是空值。我把文件放在错误的地方吗?我正在使用eclipse及其设置将类文件构建到源文件夹 - 所以这应该不是问题。
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.
我在JavaDoc中找不到任何东西让ClassLoader告诉我正在搜索什么类路径。
I can't find anything in the JavaDoc to get the ClassLoader to tell me what classpath is being searched.
推荐答案
使用 getClass()。getClassloader()
你寻找来自根路径目录的theta.properties。只需使用 getClass()。getResourceAsStream()
获取相对于该类的资源。
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.
这篇关于如何使用Java ClassLoader从类路径加载文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!