从 Java 包加载属性文件 [英] Loading a properties file from Java package
问题描述
我需要在 com.al.common.email.templates
中读取隐藏在我的包结构中的属性文件.
I need to read a properties files that's buried in my package structure in com.al.common.email.templates
.
我什么都试过了,还是搞不明白.
I've tried everything and I can't figure it out.
最后,我的代码将在 servlet 容器中运行,但我不想依赖容器做任何事情.我编写了 JUnit 测试用例,它需要在两者中都能工作.
In the end, my code will be running in a servlet container, but I don't want to depend on the container for anything. I write JUnit test cases and it needs to work in both.
推荐答案
当从 com.al.common.email.templates
包中的类加载属性时,您可以使用
When loading the Properties from a Class in the package com.al.common.email.templates
you can use
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("foo.properties");
prop.load(in);
in.close();
(添加所有必要的异常处理).
(Add all the necessary exception handling).
如果你的类不在那个包中,你需要稍微不同地获取 InputStream:
If your class is not in that package, you need to aquire the InputStream slightly differently:
InputStream in =
getClass().getResourceAsStream("/com/al/common/email/templates/foo.properties");
getResource()
/getResourceAsStream()
中的相对路径(那些没有前导/"的路径)意味着将相对于代表资源的目录搜索资源类所在的包.
Relative paths (those without a leading '/') in getResource()
/getResourceAsStream()
mean that the resource will be searched relative to the directory which represents the package the class is in.
使用 java.lang.String.class.getResource("foo.txt")
将搜索(不存在的)文件 /java/lang/String/foo.txt代码>在类路径上.
Using java.lang.String.class.getResource("foo.txt")
would search for the (inexistent) file /java/lang/String/foo.txt
on the classpath.
使用绝对路径(以/"开头的路径)意味着当前包被忽略.
Using an absolute path (one that starts with '/') means that the current package is ignored.
这篇关于从 Java 包加载属性文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!