Java 如何使用JUnit/Ant加载属性文件?
我使用的是Ant1.8,JUnit4.8.2。我正在尝试加载属性文件,但遇到一些问题。属性文件位于源目录的根目录下,我将其加载到类路径中,并在类路径中显式加载属性文件。下面是我的ant build.xml文件。下面是我如何尝试加载属性Java 如何使用JUnit/Ant加载属性文件?,java,ant,junit,Java,Ant,Junit,我使用的是Ant1.8,JUnit4.8.2。我正在尝试加载属性文件,但遇到一些问题。属性文件位于源目录的根目录下,我将其加载到类路径中,并在类路径中显式加载属性文件。下面是我的ant build.xml文件。下面是我如何尝试加载属性 private void loadTestProperties() { try { Properties prop = new Properties(); InputStream in = getClass().getR
private void loadTestProperties() {
try {
Properties prop = new Properties();
InputStream in = getClass().getResourceAsStream("db.properties");
prop.load(in);
in.close();
} catch (Exception e) {
fail("Failed to load properties: " + e.getMessage());
} // try
} // loadTestProperties
它总是以null失败(未加载属性)
有人知道加载属性文件的正确方法吗?谢谢,-Dave尝试从
getClass()加载资源。getResourceAsStream()
将导致基于类的包名查找db.properties
,即在目录(类路径中)中,如com/criticalmass/infinitiusa/…
相反,要从类路径的根加载,请尝试以下操作
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
请改为尝试“/db.properties”
。看
对于Ant,文件路径是相对于工作目录解析的。因此,如果从项目根目录运行,该文件将位于
src/${db props file}
中,这听起来不错。我认为访问ContextClassLoader的首选方法是通过当前类。所以(我认为)这会更好:getClass().getContextClassLoader().getResourceAsStream(“db.properties”);赢家Gweebz,你为什么说一种方法比另一种更可取?
InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties");
InputStream in = getClass().getResourceAsStream("db.properties");