Properties

Intro

Problem

  • Как изменить поведение программы при этом не изменяя кода самой программы?

  • Файл?

  • База данных?

  • Задать через сеть?

Solution

Properties

Properties

Properties

  • Класс Properties – это подкласс Hashtable. Он используется для хранения списков значений, в которых ключ является String, а значение также является String.

  • Класс Properties в Java используется множеством других классов. Например, это тип объекта, возвращаемый System.getProperties(), когда тот получает внешние значения.

Constructors

  • Properties()

  • Properties(Properties propDefault)

Methods

  • String getProperty(String key)

  • String getProperty(String key, String defaultProperty)

  • void list(PrintStream streamOut)

  • void list(PrintWriter streamOut)

  • void load(InputStream streamIn) throws IOException

  • Enumeration propertyNames()

  • Object setProperty(String key, String value)

  • void store(OutputStream streamOut, String description)

Examples

Example

import java.util.Map;
import java.util.Properties;
import java.util.Set;

/**
 * Java program to demonstrate Properties class to get all the system properties
 */
public class PropertiesExample2GetSystemProperties {
    /**
     * Main method for Demo
     *
     * @param args input arguments
     */
    public static void main(String[] args) {
        // get all the system properties
        Properties p = System.getProperties();

        // stores set of properties information
        Set<Map.Entry<Object, Object>> set = p.entrySet();

        // iterate over the set
        for (Map.Entry<Object, Object> entry : set) {
            // print each property
            System.out.printf("%s=%s\n", entry.getKey(), entry.getValue());
        }
    }
}

Output

java.specification.version=15
sun.management.compiler=HotSpot 64-Bit Tiered Compilers
sun.jnu.encoding=UTF-8
java.runtime.version=15.0.1+9
java.class.path=/home/rakovets/dev/course-java-basics/build/classes/java/main:/home/rakovets/dev/course-java-basics/build/resources/main
user.name=rakovets
java.vm.vendor=AdoptOpenJDK
path.separator=:
sun.arch.data.model=64
os.version=5.8.0-34-generic
user.variant=
java.runtime.name=OpenJDK Runtime Environment
file.encoding=UTF-8
java.vendor.url=https://adoptopenjdk.net/
java.vm.name=OpenJDK 64-Bit Server VM
java.vm.specification.version=15
os.name=Linux
java.vendor.version=AdoptOpenJDK
user.country=US
sun.java.launcher=SUN_STANDARD
sun.boot.library.path=/home/rakovets/.sdkman/candidates/java/15.0.1.hs-adpt/lib
sun.java.command=com.rakovets.course.javabasics.example.properties.PropertiesExample2GetSystemProperties
java.vendor.url.bug=https://github.com/AdoptOpenJDK/openjdk-support/issues
java.io.tmpdir=/tmp
jdk.debug=release
sun.cpu.endian=little
java.version=15.0.1
user.home=/home/rakovets
user.dir=/home/rakovets/dev/course-java-basics
user.language=en
os.arch=amd64
java.specification.vendor=Oracle Corporation
java.vm.specification.name=Java Virtual Machine Specification
java.version.date=2020-10-20
java.home=/home/rakovets/.sdkman/candidates/java/15.0.1.hs-adpt
file.separator=/
java.vm.compressedOopsMode=Zero based
line.separator=

java.library.path=/usr/java/packages/lib:/usr/lib64:/lib64:/lib:/usr/lib
java.vm.info=mixed mode, sharing
java.vm.specification.vendor=Oracle Corporation
java.specification.name=Java Platform API Specification
java.vendor=AdoptOpenJDK
java.vm.version=15.0.1+9
sun.io.unicode.encoding=UnicodeLittle
java.class.version=59.0

Properties file

username=rakovets
password=Fc9S42SMEfJbNVtM

Example

import java.io.FileReader;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;

/**
 * Java program to demonstrate Properties class to get information from the properties file
 */
public class PropertiesExample1 {
    /**
     * Main method for Demo
     *
     * @param args input arguments
     * @throws IOException throw IOException when work with IO
     */
    public static void main(String[] args) throws IOException {
        // get path for user.properties
        Path userPropertiesPath =
                Paths.get("src", "main", "resources", "example", "properties", "account.properties");

        // create a reader object on the properties file
        FileReader reader = new FileReader(userPropertiesPath.toFile());

        // create properties object
        Properties p = new Properties();

        // Add a wrapper around reader object
        p.load(reader);

        // access properties data
        System.out.printf("Username: '%s'\n", p.getProperty("username"));
        System.out.printf("Password: '%s'\n", p.getProperty("password"));
    }
}

Output

username=rakovets
password=Fc9S42SMEfJbNVtM

Example

import java.io.FileWriter;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Properties;

/**
 * Java program to demonstrate Properties class to create the properties file
 */
public class PropertiesExample3CreateAndWriteToFile {
    /**
     * Main method for Demo
     *
     * @param args input arguments
     * @throws IOException throw IOException when work with IO
     */
    public static void main(String[] args) throws IOException {
        // create an instance of Properties
        Properties p = new Properties();

        // add properties to it
        p.setProperty("name", "Dmitry Rakovets");
        p.setProperty("email", "dmitryrakovets@gmail.com");

        // get path for account.properties
        Path userPropertiesPath =
                Paths.get("src", "main", "resources", "example", "properties", "user.properties");

        // store the properties to a file
        p.store(new FileWriter(userPropertiesPath.toFile()), "Properties Example");
    }
}

Properties file

#Properties Example
#Fri Jan 08 10:05:19 MSK 2021
name=Dmitry Rakovets
email=dmitryrakovets@gmail.com