trong lập trình Java, Lớp Properties
là một lớp trong gói java.util
trong Java, và nó được sử dụng để quản lý các cặp key-value, trong đó cả key và value đều là các chuỗi (String). Properties
thường được sử dụng để làm việc với các tập tin cấu hình hoặc các tài nguyên văn bản.
Một tính năng quan trọng của lớp Properties
là khả năng lưu trữ và truy cập dữ liệu thông qua key như một từ điển (dictionary). Nó cũng hỗ trợ tích hợp với các phương thức để đọc và ghi dữ liệu từ và vào các tập tin thuộc tính (property files).
Dưới đây là một số phương thức quan trọng của lớp Properties
:
void setProperty(String key, String value)
: Đặt giá trị của key trongProperties
.String getProperty(String key)
: Lấy giá trị tương ứng với key từProperties
.Enumeration<?> propertyNames()
: Trả về mộtEnumeration
chứa các key củaProperties
.void load(InputStream inStream) throws IOException
: Đọc dữ liệu từ một luồng đầu vào (InputStream) và cập nhậtProperties
.void store(OutputStream out, String comments) throws IOException
: Ghi dữ liệu từProperties
vào một luồng đầu ra (OutputStream) và thêm các comment (ghi chú) tùy chọn.
Dưới đây là ví dụ về cách sử dụng lớp Properties
để đọc và ghi dữ liệu từ tập tin thuộc tính (property file):
java
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertiesExample {
public static void main(String[] args) throws IOException {
// Đọc dữ liệu từ tập tin thuộc tính (property file)
Properties properties = new Properties();
FileInputStream input = new FileInputStream("config.properties");
properties.load(input);
input.close();
// Lấy giá trị của các thuộc tính
String username = properties.getProperty("username");
String password = properties.getProperty("password");
System.out.println("Username: " + username); // Output: Username: john_doe
System.out.println("Password: " + password); // Output: Password: my_secret_password
// Ghi dữ liệu vào tập tin thuộc tính (property file)
properties.setProperty("email", "[email protected]");
properties.setProperty("is_admin", "true");
FileOutputStream output = new FileOutputStream("config.properties");
properties.store(output, "Updated properties");
output.close();
}
}
Trong ví dụ trên, chúng ta đọc dữ liệu từ tập tin thuộc tính config.properties
bằng cách sử dụng load()
và lấy giá trị của các thuộc tính thông qua getProperty()
. Sau đó, chúng ta cập nhật dữ liệu và ghi vào tập tin thuộc tính bằng cách sử dụng store()
.
Lớp Properties
rất hữu ích khi bạn cần quản lý các cấu hình ứng dụng hoặc lưu trữ các tài nguyên văn bản trong ứng dụng Java của bạn.