Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to construct properties list with defaults in java?

this code:

import java.util.Properties;
public class P {
    public static void main(String[] args) {
        Properties defaultProperties=new Properties();
        defaultProperties.put("a",1);
        System.out.println("default: "+defaultProperties);
        Properties properties=new Properties(defaultProperties);
        System.out.println("other: "+properties);
    }
}

prints:

default: {a=1}
other: {}

using java 8 in eclipse luna.

how should one construct a properties list with defaults?

like image 729
Ray Tayek Avatar asked Apr 08 '26 15:04

Ray Tayek


1 Answers

The are 2 problems with your code.

  1. The default properties don't work when you use get() and put().

You instead need to do setProperty() and 'getProperty()`.

  1. When you print the properties file, it wont include the default properties. The toString() method is not so sophesticated.

Use this instead:

Properties defaultProperties=new Properties();
defaultProperties.setProperty("a","s");
System.out.println("default: "+defaultProperties);
Properties properties=new Properties(defaultProperties);
System.out.println("other: "+properties.getProperty("a"));
like image 69
Codebender Avatar answered Apr 10 '26 05:04

Codebender



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!