[英]The getProperty is returning null even after loading the property file in Java
What is wrong in the below code. 下面的代码有什么问题。 Everything seems correct and no exceptions when executing. 一切似乎都是正确的,执行时也没有例外。 I have double verified that the test property value is there in config.properties file. 我已再次验证config.properties文件中是否存在测试属性值。
@BeforeClass
public void propertyLoading() {
System.out.println("in beforeclass");
prop = new Properties();
ClassLoader classLoader = ClassLoader.getSystemClassLoader();
try {
System.out.println("path : "+classLoader.getResource("config.properties").getFile().toString());
input = new FileInputStream(new File(classLoader.getResource("config.properties").getFile()));
prop.load(input);
}
catch (Exception e) {
e.printStackTrace();
}
try {
if (input != null)
input.close();
}
catch (IOException e) {
e.printStackTrace();
}
System.out.println("test : "+System.getProperty("test"));
}
config.properties file contents below; config.properties文件的内容如下;
test=aaaa
Because you are using the System properties, this is not the same as runtime properties that you are trying to use 因为您使用的是系统属性,所以这与您尝试使用的运行时属性不同
System.getProperty
while you should be calling your Properties object that you created a few lines above 当您应该调用在上面创建几行的Properties对象时
prop.getProperty("test")
If you want to read your properties from System.getProperty() call 如果您想从System.getProperty()调用中读取属性
System.setProperties(prop);
after reading your properties from file 从文件中读取属性后
(On the sideline, use try with resources when possible https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html ) (在副业上,尽可能尝试使用资源https://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html )
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.