2012-02-13 273 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