我在 src/test/java/com/pp/utils 中有一个 java 文件。我需要从此 Java 文件访问 src/test/resources 内的属性文件 example.properties。
我尝试过:
Properties prop = new Properties();
InputStream input = null;
try {
input = new FileInputStream("example.properties");
// load a properties file
prop.load(input);
// get the property value and print it out
System.out.println(prop.getProperty("key1"));
} catch (IOException ex) {
ex.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
这会产生 FileNotFound 异常。路径应该是什么?或者我还可以将属性文件放置在哪里以便可以拾取它?
最佳答案
尝试
InputStream inputStream = getClass().getResourceAsStream("/example.properties");
为了清楚起见,假设您的属性文件位于/src/test/resources 中,这是类路径的根目录,因此是/example.properties。
关于java - 访问 Maven 项目中的属性文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35503211/