Question

I have a piece of code defining a property like this:

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();

Which saves a properties file OK

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

When I create another property and perform a load() on it, it loads OK. get(DEFINED_KEY) returns the value specified for DEFINED_PROPERTY, but getProperty(DEFINED_KEY) returns null. What's up with this?

Was it helpful?

Solution

I don't see anything wrong with your code... here's my test:-

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));
}

The generated output:-

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top