Home > Java > javaTutorial > How to use Properties class in Java?

How to use Properties class in Java?

DDD
Release: 2024-10-31 08:35:30
Original
693 people have browsed it

¿Cómo usar la clase Properties en Java?

Introduction

When we work on a Java application, it is common that we need to work with some configurations, for example, the URL of a database, the port of a server, among others. Instead of hardcoding these settings directly into the code, we're interested in getting them from somewhere external to the code, such as a properties file. Or even be able to save configurations at runtime to read them later.

In any of these cases, we can develop our own solutions for certain scenarios, for example, create a text file and in the first line save the URL of the database, in the second line the server port, etc. . But this can be tedious and error-prone, so a more robust and scalable solution is needed. For this type of case, Java provides us with a very simple and efficient solution to use, the Properties class.

What is the Properties class?

Properties is a class found in the java.util package that allows us to save configurations both temporarily in memory and persistently in a properties file, so we can later read them and use them in our application. By creating an instance of the Properties class, you get an object that behaves like a dictionary, where each configuration is saved as a key-value pair.

Using the Properties class

To begin, an instance of the Properties class must be created.

Properties props = new Properties();
Copy after login
Copy after login
Copy after login

By inheriting from the HashTable class (which in turn inherits from Dictionary), within the Properties class we can see that it has methods of the Object type, when in reality the values ​​are expected to be character strings or String, and not , it is not necessary to cast a String every time you work with a value. In this way, although there are common methods of a map within the instance, in most cases it will not be necessary to use them. For example, instead of using get(Object key) you can use getProperty(String key).

Define properties

To define a property, the setProperty(String key, String value) method is used, as its name indicates, this method receives two parameters, the key (how you want to call the property) and the value (the property value), considering that both parameters are always expected to be of type String.

Properties props = new Properties();
props.setProperty("DB_HOST", "localhost");
props.setProperty("DB_PORT", "3306");
props.setProperty("DB_USER", "root");
props.setProperty("DB_PASS", "p4ssw0rd");
Copy after login
Copy after login
Copy after login

Get a property

To obtain a property you can use the getProperty(String key) method, which receives as a parameter the key of the property you want to obtain. If the property does not exist, null will be returned.

Properties props = new Properties();
Copy after login
Copy after login
Copy after login

To avoid obtaining null in case a property does not exist, you can use the getProperty(String key, String defaultValue) method, which receives a default value as a second parameter.

Properties props = new Properties();
props.setProperty("DB_HOST", "localhost");
props.setProperty("DB_PORT", "3306");
props.setProperty("DB_USER", "root");
props.setProperty("DB_PASS", "p4ssw0rd");
Copy after login
Copy after login
Copy after login

Iterate over properties

As it is a map type object (although it is not recommended to use HashTable methods), it has the entrySet() method, but as you can see it is of type Object, an alternative to iterate over all the properties is to use the stringPropertyNames() method, which returns a set of character strings with all the property keys (the returned values ​​are in no specific order).

var API_URL = props.getProperty("API_URL");
System.out.println(API_URL);

// Output
null
Copy after login
Copy after login

A faster way to display all properties is to use the list(PrintStream out) method, which prints all properties to the output stream passed as a parameter, for example System.out.

var API_URL = props.getProperty("API_URL", "http://api.example.com");
System.out.println(API_URL);

// Output
http://api.example.com
Copy after login
Copy after login

Save properties to a file

Properties provides the store() and storeToXML() methods so that properties can be saved in a properties (key=value) format and in a XML format (this can be useful if the properties will be used in different environments) respectively. Do not use the save() method since it is obsolete and its use is not recommended, since it does not throw exceptions in case an error occurs.

Before saving the properties to a file, we can do the following to verify by console what is actually saved using the store() and System.out method, it is important to somehow control the exception that is thrown.

for (String prop : props.stringPropertyNames()) {
    System.out.println(prop + " = " + props.getProperty(prop));
}

// Output
DB_PORT = 3306
DB_PASS = p4ssw0rd
DB_USER = root
DB_HOST = localhost
Copy after login

Analyzing the result, you can see that in the first line the comment that is passed as the second argument is saved (it does not matter if it is an empty string, if it is null it is not printed), in the second line it is saved the date and time in which the properties were saved, and starting from the third line the properties are saved in the format key=value.

If the storeToXML() method is used, a file with the following content will be obtained:

props.list(System.out);

// Output
-- listing properties --
DB_PORT=3306
DB_PASS=p4ssw0rd
DB_USER=root
DB_HOST=localhost
Copy after login

To save the properties in a file called db.properties you can do the following:

props.store(System.out, "Database Configuration");

// Output
#Database Configuration
#Thu Oct 10 11:06:04 CST 2024
DB_HOST=localhost
DB_PASS=p4ssw0rd
DB_PORT=3306
DB_USER=root
Copy after login

Once executed, and if no exception is thrown, you will see that a file with the name db.properties has been created in the directory where the program was executed, with the following content:

props.storeToXML(System.out, "Database Configuration");

// Output
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE properties SYSTEM "http://java.sun.com/dtd/properties.dtd">
<properties>
<comment>Database Configuration</comment>
<entry key="DB_PORT">3306</entry>
<entry key="DB_PASS">p4ssw0rd</entry>
<entry key="DB_USER">root</entry>
<entry key="DB_HOST">localhost</entry>
</properties>
Copy after login

To save the properties in XML format, simply change the store() method to storeToXML().

Properties props = new Properties();
Copy after login
Copy after login
Copy after login

Load properties from a file

Suppose some property has been modified or a new one added within the db.properties or db.properties.xml file, to load the properties from either of the two files, either in properties or XML, the load() and loadFromXML() methods can be used respectively. It is important to somehow control the exception that is thrown in case the file does not exist or cannot be read.

Properties props = new Properties();
props.setProperty("DB_HOST", "localhost");
props.setProperty("DB_PORT", "3306");
props.setProperty("DB_USER", "root");
props.setProperty("DB_PASS", "p4ssw0rd");
Copy after login
Copy after login
Copy after login
var API_URL = props.getProperty("API_URL");
System.out.println(API_URL);

// Output
null
Copy after login
Copy after login

Once the properties are loaded, they can be displayed in the console to verify that they have been loaded correctly.

var API_URL = props.getProperty("API_URL", "http://api.example.com");
System.out.println(API_URL);

// Output
http://api.example.com
Copy after login
Copy after login

Conclusion

As we have seen, the Properties class allows us to work with property or configuration files in an efficient and simple way, both to save and read properties, which is interesting to know and use in our Java applications.

The above is the detailed content of How to use Properties class in Java?. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template