Java properties files syntax

# Properties Class

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

# Loading properties

To load a properties file bundled with your application:

public class Defaults  public static Properties loadDefaults()  try (InputStream bundledResource = Defaults.class.getResourceAsStream("defaults.properties"))  Properties defaults = new Properties(); defaults.load(bundledResource); return defaults; > catch (IOException e)  // Since the resource is bundled with the application, // we should never get here. throw new UncheckedIOException( "defaults.properties not properly packaged" + " with application", e); > > > 

# Property files caveat: trailing whitespace

Take a close look at these two property files which are seemingly completely identical:

enter image description here

except they are really not identical:

enter image description here

(screenshots are from Notepad++)

Since trailing whitespace is preserved the value of lastName would be «Smith» in the first case and «Smith » in the second case.

Very rarely this is what users expect and one and can only speculate why this is the default behavior of Properties class. It is however easy to create an enhanced version of Properties that fixes this problem. The following class, TrimmedProperties, does just that. It is a drop-in replacement for standard Properties class.

import java.io.FileInputStream; import java.io.FileReader; import java.io.IOException; import java.io.InputStream; import java.io.Reader; import java.util.Map.Entry; import java.util.Properties; /** * Properties class where values are trimmed for trailing whitespace if the * properties are loaded from a file. * * 

* In the standard class trailing * whitespace is always preserved. When loading properties from a file such * trailing whitespace is almost always unintentional. This class fixes * this problem. The trimming of trailing whitespace only takes place if the * source of input is a file and only where the input is line oriented (meaning * that for example loading from XML file is not changed by this class). * For this reason this class is almost in all cases a safe drop-in replacement * for the standard Properties * class. * *

* Whitespace is defined here as any of space (U+0020) or tab (U+0009). * * */ public class TrimmedProperties extends Properties /** * Reads a property list (key and element pairs) from the input byte stream. * *

Behaves exactly as * with the exception that trailing whitespace is trimmed from property values * if inStream is an instance of FileInputStream. * * @see java.util.Properties#load(java.io.InputStream) * @param inStream the input stream. * @throws IOException if an error occurred when reading from the input stream. */ @Override public void load(InputStream inStream) throws IOException if (inStream instanceof FileInputStream) // First read into temporary props using the standard way Properties tempProps = new Properties(); tempProps.load(inStream); // Now trim and put into target trimAndLoad(tempProps); > else super.load(inStream); > > /** * Reads a property list (key and element pairs) from the input character stream in a simple line-oriented format. * *

Behaves exactly as * with the exception that trailing whitespace is trimmed on property values * if reader is an instance of FileReader. * * @see java.util.Properties#load(java.io.Reader) > * @param reader the input character stream. * @throws IOException if an error occurred when reading from the input stream. */ @Override public void load(Reader reader) throws IOException if (reader instanceof FileReader) // First read into temporary props using the standard way Properties tempProps = new Properties(); tempProps.load(reader); // Now trim and put into target trimAndLoad(tempProps); > else super.load(reader); > > private void trimAndLoad(Properties p) for (EntryObject, Object> entry : p.entrySet()) if (entry.getValue() instanceof String) put(entry.getKey(), trimTrailing((String) entry.getValue())); > else put(entry.getKey(), entry.getValue()); > > > /** * Trims trailing space or tabs from a string. * * @param str * @return */ public static String trimTrailing(String str) if (str != null) // read str from tail until char is no longer whitespace for (int i = str.length() - 1; i >= 0; i--) if ((str.charAt(i) != ' ') && (str.charAt(i) != '\t')) return str.substring(0, i + 1); > > > return str; > >

# Saving Properties as XML

Storing Properties in a XML File

The way you store properties files as XML files is very similar to the way you would store them as .properties files. Just instead of using the store() you would use storeToXML() .

public void saveProperties(String location) throws IOException // make new instance of properties Properties prop = new Properties(); // set the property values prop.setProperty("name", "Steve"); prop.setProperty("color", "green"); prop.setProperty("age", "23"); // check to see if the file already exists File file = new File(location); if (!file.exists()) file.createNewFile(); > // save the properties prop.storeToXML(new FileOutputStream(file), "testing properties with xml"); > 

When you open the file it will look like this.

screenshot of the file made

Loading Properties from a XML File

Now to load this file as a properties you need to call the loadFromXML() instead of the load() that you would use with regular .propeties files.

public static void loadProperties(String location) throws FileNotFoundException, IOException // make new properties instance to load the file into Properties prop = new Properties(); // check to make sure the file exists File file = new File(location); if (file.exists()) // load the file prop.loadFromXML(new FileInputStream(file)); // print out all the properties for (String name : prop.stringPropertyNames()) System.out.println(name + "=" + prop.getProperty(name)); > > else  System.err.println("Error: No file found at: " + location); > > 

When you run this code you will get the following in the console:

age=23 color=green name=Steve 

# Syntax

# Remarks

(opens new window) 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

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

  • 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

(opens new window) 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

(opens new window) . You can then load the file using load(Reader)

(opens new window) 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

Источник

Properties

Properties - 1

В Java принято делать программы гибкими и легко настраиваемыми. Иногда еще говорят легко конфигурируемыми (от конфигурация).

Например, твоя программа раз в час копирует файлы из некоторой директории, архивирует их и отсылает тебе на email. Для этого программе надо знать директорию, откуда брать файлы и email, куда их посылать. Такие данные принято хранить не в коде программы, а в отдельных файлах свойств – properties-файлах.

Данные в таком файле хранятся в виде пар ключ-значение, разделенные знаком равно.

Файл data.properties directory=c:/text/downloads email=zapp@javarush.ru

Слева от знака равно – имя (ключ), справа – значение.

— Т.е. это что-то типа текстового представления HashMap?

Для удобной работы с такими файлами в Java есть специальный класс – Properties. Класс Properties унаследован от Hashtable. Его даже можно рассматривать как HashTable, который умеет загружать себя из файла.

Метод Описание
void load(Reader reader) Загружает свойства из файла, представленного объектом Reader
void load(InputStream inStream) Загружает свойства из файла, представленного объектом InputStream
void loadFromXML(InputStream in) Загружает свойства из XML-файла
Object get(Object key) Возвращает значение по ключу. Метод унаследован от HashTable
String getProperty(String key) Возвращает значение свойства (строку) по ключу
String getProperty(String key, String defaultValue) Возвращает значение свойства по ключу или defaultValue, если такого ключа нет
Set stringPropertyNames() Возвращает список всех ключей

Т.е. фактически тебе нужно выполнить всего две операции – загрузить в объект Properties данные из какого-нибудь файла, а затем получить эти свойства с помощью метода getProperty(). Ну и не забывай, что можешь пользоваться объектом Properties как HashMap.

//файл, который хранит свойства нашего проекта File file = new File("c:/data.properties"); //создаем объект Properties и загружаем в него данные из файла. Properties properties = new Properties(); properties.load(new FileReader(file)); //получаем значения свойств из объекта Properties String email = properties.getProperty("email"); String directory = properties.getProperty("directory"); //получаем числовое значение из объекта Properties int maxFileSize = Integer.parseInt(properties.getProperty("max.size", "10000"));

— Ага. Т.е. мы создаем объект Properties, затем передаем в него файл. В метод load, а затем просто вызываем getProperty. Так?

— А ты еще говорил, что им можно пользоваться как HashMap? Что ты имел в виду?

— Класс Properties унаследован от Hashtable, а это – тот же HashMap, просто все методы его синхронизированы. Вот так можно просто вывести на экран все значения из файла свойств:

//получаем файл со свойствами File file = new File("c:/data.properties"); //создаем объект Properties и загружаем в него данные из файла. Properties properties = new Properties(); properties.load(new FileReader(file)); //проходимся по всем ключам и печатаем все их значения на консоль for (String key : properties.stringPropertyNames()) < System.out.println(properties.get(key)); >

— Ага. Вроде все стало на свои места. Спасибо, Риша, буду пользоваться такой крутой штукой.

Источник

Простой пример работы с Property файлами в Java

Property файлы присутствуют практически в каждом проекте, и сейчас я вам покажу простой пример их использования, а также расскажу, зачем они и где используются.

Шаг 0. Создание проекта

Начнем с того что создадим простой Maven проект, указав название и имя пакета:

prop_1

Структура, которая получится в конце проекта довольно таки простая.

Как видите у нас только два файла, первый – Main.java, а второй – config.properties.

Шаг 2. Добавляем конфигурационные данные в проперти файл

Проперти файлы либо файлы свойств – предназначены, для того чтобы хранить в них какие-то статические данные необходимые проект, например логин и пароль к БД.

Давайте добавим в наш config.properties логин и пароль (это любые данные, для того чтобы продемонстрировать работу с property файлами).

Содержимое config.properties:

db.host = http://localhost:8888/mydb db.login = root db.password = dbroot

ключ> – это уникальное имя, по которому можно получить доступ к значению, хранимому под этим ключом.

значение> – это текст, либо число, которое вам необходимо для выполнения определённой логики в вашей программе.

Шаг 3. Получаем Property данные

Как можно видеть в структуре проекта выше, там есть класс Main.java давайте его создадим и напишем в нем следующее:

package com.devcolibir.prop; import java.io.*; import java.util.Properties; public class Main < public static void main(String[] args) < FileInputStream fis; Properties property = new Properties(); try < fis = new FileInputStream("src/main/resources/config.properties"); property.load(fis); String host = property.getProperty("db.host"); String login = property.getProperty("db.login"); String password = property.getProperty("db.password"); System.out.println("HOST: " + host + ", LOGIN: " + login + ", PASSWORD: " + password); >catch (IOException e) < System.err.println("ОШИБКА: Файл свойств отсуствует!"); >> >

Обращаясь к property.getProperty(ключ>) – вы получаете его значение.

Вот такой краткий, но думаю познавательный урок.

Источник

Читайте также:  What is an interface type in java
Оцените статью