为什么getProperty()返回null?

时间:2012-02-13 16:40:35

标签: java properties getproperty

我有一段代码定义了这样的属性:

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。怎么了?

1 个答案:

答案 0 :(得分: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