问题
我需要读取埋藏在我的包结构中的属性文件com.al.common.email.templates
。
我已经尝试了一切,我无法理解。
最后,我的代码将在servlet容器中运行,但我不想依赖于容器。我编写了JUnit测试用例,它需要兼顾两者。
#1 热门回答(220 赞)
从包com.al.common.email.templates
中的类加载属性时,你可以使用
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("foo.properties");
prop.load(in);
in.close();
(添加所有必要的异常处理)。
如果你的类不在该包中,则需要稍微不同地获取InputStream:
InputStream in =
getClass().getResourceAsStream("/com/al/common/email/templates/foo.properties");
ingetResource()
/ getResourceAsStream()
中的相对路径(没有前导'/'的路径)表示将相对于表示该类所在的包的目录搜索资源。
使用java.lang.String.class.getResource("foo.txt")
将在类路径中搜索(不存在)file/java/lang/String/foo.txt
。
使用绝对路径(以'/'开头的路径)意味着忽略当前包。
#2 热门回答(44 赞)
要添加Joachim Sauer的答案,如果你需要在静态环境中执行此操作,你可以执行以下操作:
static {
Properties prop = new Properties();
InputStream in = CurrentClassName.class.getResourceAsStream("foo.properties");
prop.load(in);
in.close()
}
(与以前一样,例外处理被省略了。)
#3 热门回答(13 赞)
以下两种情况涉及从名为TestLoadProperties
的示例类加载属性文件。
案例1:使用ClassLoader
InputStream inputStream = TestLoadProperties.class.getClassLoader()
.getResourceAsStream("A.config");
properties.load(inputStream);
加载属性文件
在这种情况下,属性文件必须位于root/src
目录中才能成功加载。
情况2:不使用ClassLoader
InputStream inputStream = getClass().getResourceAsStream("A.config");
properties.load(inputStream);
加载属性文件
在这种情况下,属性文件必须与6TestLoadProperties.class
文件位于同一目录中才能成功加载。
注意:TestLoadProperties.java
和TestLoadProperties.class
是两个不同的文件。前者.java
文件通常位于项目的src/
目录中,而后者.class
文件通常位于其bin/
目录中。