Stats

183 Contributors: 10
2017-06-09
Licensed under: CC-BY-SA

Not affiliated with Stack Overflow
Rip Tutorial: info@zzzprojects.com

Download eBook

Properties Class

Download java eBook

Introduction

The properties object contains key and value pair both as a string. The java.util.Properties class is the subclass of Hashtable.

It can be used to get property value based on the property key. The Properties class provides methods to get data from properties file and store data into properties file. Moreover, it can be used to get properties of system.

Advantage of properties file

Recompilation is not required, if information is changed from properties file: If any information is changed from

Syntax

  • In a properties file:
  • key=value
  • #comment

Remarks

A Properties object is a Map whose keys and values are Strings by convention. Although the methods of Map can be used to access the data, the more type-safe methods getProperty, setProperty, and stringPropertyNames are usually used instead.

Properties are frequently stored in Java property files, which are simple text files. Their format is documented thoroughly in the Properties.load method. In summary:

  • Each key/value pair is a line of text with whitespace, equals (=), or colon (:) between the key and the value. The equals or colon may have any amount of whitespace before and after it, which is ignored.
  • Leading whitespace is always ignored, trailing whitespace is always included.
  • A backslash can be used to escape any character (except lowercase u).
  • A backslash at the end of the line indicates the next line is a continuation of the current line. However, as with all lines, leading whitespace in the continuation line is ignored.
  • Just like in Java source code, \u followed by four hexadecimal digits represents a UTF-16 character.

Most frameworks, including Java SE’s own facilities like java.util.ResourceBundle, load property files as InputStreams. When loading a property file from an InputStream, that file is may only contain ISO 8859-1 characters (that is, characters in the 0–255 range). Any other characters must be represented as \u escapes. However, you can write a text file in any encoding and use the native2ascii tool (which comes with every JDK) to do that escaping for you.

If you are loading a property file with your own code, it can be in any encoding, as long as you create a Reader (such as an InputStreamReader) based on the corresponding Charset. You can then load the file using load(Reader) instead of the legacy load(InputStream) method.

You can also store properties in a simple XML file, which allows the file itself to define the encoding. Such a file can be loaded with the loadFromXML method. The DTD describing the structure of such XML files is located at http://java.sun.com/dtd/properties.dtd .

Related Examples