search
HomeJavajavaTutorialHow to use Properties class in Java?

¿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();

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");

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();

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");

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

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

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

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

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

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"?>

<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>

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

Properties props = new Properties();

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");
var API_URL = props.getProperty("API_URL");
System.out.println(API_URL);

// Output
null

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

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!

Statement
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
How does platform independence benefit enterprise-level Java applications?How does platform independence benefit enterprise-level Java applications?May 03, 2025 am 12:23 AM

Java is widely used in enterprise-level applications because of its platform independence. 1) Platform independence is implemented through Java virtual machine (JVM), so that the code can run on any platform that supports Java. 2) It simplifies cross-platform deployment and development processes, providing greater flexibility and scalability. 3) However, it is necessary to pay attention to performance differences and third-party library compatibility and adopt best practices such as using pure Java code and cross-platform testing.

What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?What role does Java play in the development of IoT (Internet of Things) devices, considering platform independence?May 03, 2025 am 12:22 AM

JavaplaysasignificantroleinIoTduetoitsplatformindependence.1)Itallowscodetobewrittenonceandrunonvariousdevices.2)Java'secosystemprovidesusefullibrariesforIoT.3)ItssecurityfeaturesenhanceIoTsystemsafety.However,developersmustaddressmemoryandstartuptim

Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.Describe a scenario where you encountered a platform-specific issue in Java and how you resolved it.May 03, 2025 am 12:21 AM

ThesolutiontohandlefilepathsacrossWindowsandLinuxinJavaistousePaths.get()fromthejava.nio.filepackage.1)UsePaths.get()withSystem.getProperty("user.dir")andtherelativepathtoconstructthefilepath.2)ConverttheresultingPathobjecttoaFileobjectifne

What are the benefits of Java's platform independence for developers?What are the benefits of Java's platform independence for developers?May 03, 2025 am 12:15 AM

Java'splatformindependenceissignificantbecauseitallowsdeveloperstowritecodeonceandrunitonanyplatformwithaJVM.This"writeonce,runanywhere"(WORA)approachoffers:1)Cross-platformcompatibility,enablingdeploymentacrossdifferentOSwithoutissues;2)Re

What are the advantages of using Java for web applications that need to run on different servers?What are the advantages of using Java for web applications that need to run on different servers?May 03, 2025 am 12:13 AM

Java is suitable for developing cross-server web applications. 1) Java's "write once, run everywhere" philosophy makes its code run on any platform that supports JVM. 2) Java has a rich ecosystem, including tools such as Spring and Hibernate, to simplify the development process. 3) Java performs excellently in performance and security, providing efficient memory management and strong security guarantees.

How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?How does the JVM contribute to Java's 'write once, run anywhere' (WORA) capability?May 02, 2025 am 12:25 AM

JVM implements the WORA features of Java through bytecode interpretation, platform-independent APIs and dynamic class loading: 1. Bytecode is interpreted as machine code to ensure cross-platform operation; 2. Standard API abstract operating system differences; 3. Classes are loaded dynamically at runtime to ensure consistency.

How do newer versions of Java address platform-specific issues?How do newer versions of Java address platform-specific issues?May 02, 2025 am 12:18 AM

The latest version of Java effectively solves platform-specific problems through JVM optimization, standard library improvements and third-party library support. 1) JVM optimization, such as Java11's ZGC improves garbage collection performance. 2) Standard library improvements, such as Java9's module system reducing platform-related problems. 3) Third-party libraries provide platform-optimized versions, such as OpenCV.

Explain the process of bytecode verification performed by the JVM.Explain the process of bytecode verification performed by the JVM.May 02, 2025 am 12:18 AM

The JVM's bytecode verification process includes four key steps: 1) Check whether the class file format complies with the specifications, 2) Verify the validity and correctness of the bytecode instructions, 3) Perform data flow analysis to ensure type safety, and 4) Balancing the thoroughness and performance of verification. Through these steps, the JVM ensures that only secure, correct bytecode is executed, thereby protecting the integrity and security of the program.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.