[英]How to get values from properties file in Java by a custom method
我有以下代碼,我試圖從屬性文件中獲取一些值。 我想要的是有一個getData()方法,它將接收一個包含屬性文件中的鍵的String參數。 使用下面的代碼,我總是得到“null”而不是指定鍵的值。 有什么我沒想到的嗎?
public class PropertiesManager {
static private PropertiesManager _instance = null;
private static Properties props;
protected PropertiesManager(){
props = new Properties();
try{
props.load(PropertiesManager.class.getClassLoader().getResourceAsStream("config_keys.properties"));
}
catch(Exception e){
System.out.println("error" + e);
}
}
public static PropertiesManager getInstance(){
if (_instance == null) {
_instance = new PropertiesManager();
}
return _instance;
}
public static String getData(String key){
if(props != null){
props.getProperty(key);
}
return null;
}
public static void main(String[] args){
System.out.println(getData(Constants.REG_ADDRESS));
}
}
您似乎忘記添加return
關鍵字:
if(props != null){
return props.getProperty(key);
}
public static String getData(String key){
if(props != null){
props.getProperty(key);
}
return null;
}
應該:
public static String getData(String key){
return props.getProperty(key);
}
你總是從getData()
方法返回null
。所以改變它
public static String getData(String key){
if(props != null){
return props.getProperty(key);
}
return null;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.