2012-02-13 241 views
1

我有一段代碼,定義這樣一個屬性:爲什麼getProperty()返回null?

public static final String DEFINED_KEY = "definedKey"; 
public static final String DEFINED_PROPERTY = "definedProperty"; 

// [...] 

File f = File.createTempFile("default", ".properties"); 
PrintWriter pw = new PrintWriter(f); 

Properties pp = new Properties(); 
pp.setProperty(DEFINED_KEY, DEFINED_PROPERTY); 
pp.store(pw, "Automatically defined"); 
pw.close(); 

從而節省了屬性文件確定

#No comments 
#Mon Feb 13 17:25:12 CET 2012 
definedKey=definedProperty 

當我創建另一個屬性,並在其上執行一個load(),它加載確定。 get(DEFINED_KEY)返回爲DEFINED_PROPERTY指定的值,但getProperty(DEFINED_KEY)返回null。這是怎麼回事?

+2

這一切看起來不錯。其他的一定是錯的。顯示代碼以加載屬性和兩個調用get/getProperty()。 – 2012-02-13 16:44:31

+1

'getProperty(key)'返回'super.get(key)'結果,除非它是非String。然後它試圖從'defaults'獲取數據。檢查get()爲你返回一個String對象,否則你的輸入有問題。 – 2012-02-13 16:49:32

+0

@AlexanderPavlov是的,當場。 – 2012-02-13 17:03:34

回答

1

我沒有看到任何你的代碼錯誤...這裏是我的測試: -

public static final String DEFINED_KEY = "definedKey"; 
public static final String DEFINED_PROPERTY = "definedProperty"; 

public void run() throws Exception { 
    // your code 
    File f = File.createTempFile("default", ".properties"); 
    PrintWriter pw = new PrintWriter(f); 
    Properties pp = new Properties(); 
    pp.setProperty(DEFINED_KEY, DEFINED_PROPERTY); 
    pp.store(pw, "Automatically defined"); 
    pw.close(); 

    // examining the generated properties file 
    System.out.println("Reading from properties file..."); 
    System.out.println("------------"); 
    Scanner scanner = new Scanner(f); 
    while (scanner.hasNextLine()) { 
     System.out.println(scanner.nextLine()); 
    } 
    System.out.println("------------"); 

    // loading properties file 
    Properties p = new Properties(); 
    p.load(new FileInputStream(f)); 

    System.out.println("p.get(DEFINED_KEY): " + p.get(DEFINED_KEY)); 
    System.out.println("p.getProperty(DEFINED_KEY): " + p.getProperty(DEFINED_KEY)); 
} 

生成的輸出: -

Reading from properties file... 
------------ 
#Automatically defined 
#Mon Feb 13 11:00:42 CST 2012 
definedKey=definedProperty 
------------ 
p.get(DEFINED_KEY): definedProperty 
p.getProperty(DEFINED_KEY): definedProperty 
+0

上述兩個評論指出了正確的答案。你的測試是正確的,我正在用一些額外的查找包裝Java'Properties'類。 – 2012-02-13 17:07:02