27

I have a properties file, named prop.properties. In my main code, I have both System.getProperty() and properties.getProperty().

My question is: are they both get property from prop.properties or they will get property from different places, properties.getProperty() get property from prop.properties and System.getProperty() get property from other place.

blackpanther
  • 10,998
  • 11
  • 48
  • 78
Jay Zhang
  • 629
  • 3
  • 9
  • 13
  • 1
    Depends on where `properties` came from. If `Properties properties = System.getProperties();`, then yes, they will be the same. If `Properties propertes = new Properties();`, then no, they won't be. – CodeBlind Jun 17 '13 at 15:46

3 Answers3

46

System.getProperty() gets a property as defined by the JVM (either the JVM itself or any -D options you may have passed at the command line). The list of defined properties can be found here (thanks @NikitaBeloglazov).

properties.getProperty() is the result of someone having initialized an object of type Properties. They are not the same, though you can get what System has as a Properties instance.

A Properties object is very often the result of loading a Java property file (see here for how this is done)

Community
  • 1
  • 1
fge
  • 119,121
  • 33
  • 254
  • 329
15

System.getProperty(propName) is a shortcut for System.getProperties().getProperty(propName).

However java.util.Properties is just a subclass of java.utils.Hashtable, so its instance may be created everywhere in code and populated with any data. Obviously code

Properties props = System.getProperties();
props.getProperty("os.name");

is the same as

System.getProperty("os.name");

However

Properties props = new Properties();
props.load(new FileInputStream("myprops.properties"))
props.getProperty("os.name");

is not the same.

AlexR
  • 114,158
  • 16
  • 130
  • 208
4

The System class refers to the JVM you are running (which would get info from your OS). When you use getProperty on System you get actual properties.

The Property class is basically a glorified hash table. You can completely define it yourself, so when you do getProperty() you get the results that you set up. The usefulness of the Property class is that it has a built in XML parser so you can read in properties from a file.

David says Reinstate Monica
  • 19,209
  • 22
  • 79
  • 122