+2

Java - Ví dụ về thao tác với Properties file

Thông thường, properties file trong Java được sử dụng để lưu trữ dữ liệu cấu hình dự án hoặc các thông số cài đặt một cách rất hiệu quả. Có thể thấy trong các framework java thông dụng thì file properties được sử dụng khá phổ biến. Qua bài viết này, chúng ta sẽ cùng tìm hiểu về cách đọc và ghi dữ liệu vào properties file.

Properties

Properties là các giá trị cấu hình được quản lý như các cặp key/value pairs. Trong mỗi cặp key/value đều là các giá trị kiểu String. Key được dùng để xác định, và được sử dụng để lấy ra giá trị. Ví dụ: ứng dụng có khả năng tải tệp có thể sử dụng thuộc tính có tên "download.lastDirectory" để theo dõi thư mục được sử dụng cho lần tải cuối cùng.

Java cung cấp lớp java.util.Properties để quản lý các properties. Lớp này cung cấp một số các phương thức như sau:

  • Tải các cặp key/value vào một đối tượng Properties
  • Lấy ra một giá trị dựa vào key
  • Liệt kê các key và giá trị của từng key,
  • Lưu các properties vào một stream.
  • ...

Lớp Properties kế thừa từ lớp java.util.Hashtable. Vì vậy nó có một số phương thức được kế thừa từ Hashtable như sau:

  • Thử nghiệm để xem một khóa hoặc giá trị cụ thể có trong đối tượng Properties
  • Loại bỏ một chìa khóa và giá trị của nó
  • thêm một cặp khóa / giá trị vào danh sách thuộc tính
  • liệt kê các giá trị hoặc các key
  • lấy ra một giá trị bằng khóa của nó
  • Tìm ra nếu đối tượng Properties trống
  • ...

Các cân nhắc về bảo mật: Quyền truy cập vào properties phải được sự chấp thuận của security manager hiện tại. Các đoạn code ví dụ trong phần này được giả định là thuộc các ứng dụng độc lập(standalone applications), mà theo mặc định, không có security manager.

1. Ghi vào properties file

Thiết lập giá trị của thuộc tính và lưu nó vào properties file có tên là config.properties

package vuta.properties.example;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;

public class WriteProperties {
	public static void main(String[] args) {
		Properties prop = new Properties();
		OutputStream output = null;
		try {
			output = new FileOutputStream("config.properties");

			// set the properties value
			prop.setProperty("remote.server", "192.168.1.100");
			prop.setProperty("remote.server.port", "8080");
			prop.setProperty("remote.user", "vuta");
			prop.setProperty("remote.password", "bimat");

			// save properties to project root folder
			prop.store(output, null);
		} catch (IOException io) {
			io.printStackTrace();
		} finally {
			if (output != null) {
				try {
					output.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}

		}
	}
}

Sau khi run, file config.properties sẽ được sinh ra với nội dung như sau:

#Sat Dec 02 16:25:28 ICT 2017 remote.user=vuta remote.server.port=8080 remote.password=bimat remote.server=192.168.1.100

2. Đọc properties file

package vuta.properties.example;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class LoadProperties {
	public static void main(String[] args) {
		Properties prop = new Properties();
		InputStream input = null;
		try {
			input = new FileInputStream("config.properties");
			// load a properties file
			prop.load(input);

			// get the property value and print it out
			prop.entrySet().forEach(e -> System.out.println(e.getKey() + " : " + e.getValue()));
		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}
}

Sau khi run kết quả như sau

remote.server.port : 8080 remote.user : vuta remote.password : bimat remote.server : 192.168.1.100

3. Đọc properties file từ classpath

Giả sử file "config.properties" nằm trong thư mục gốc của classpath (ví dụ nằm trong thư mục /src với cấu hình trong file .classpath như sau <classpathentry kind="src" path="src"/>)

package vuta.properties.example;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

public class LoadPropertiesFromClasspath {

	public static void main(String[] args) {
		Properties prop = new Properties();
		InputStream input = null;
		try {
			String filename = "config.properties";
			input = LoadPropertiesFromClasspath.class.getClassLoader().getResourceAsStream(filename);
			if (input == null) {
				System.out.println("Sorry, unable to find " + filename);
				return;
			}

			// load a properties file from class path, inside static method
			prop.load(input);

			// get the property value and print it out
			prop.entrySet().forEach(e -> System.out.println(e.getKey() + " : " + e.getValue()));

		} catch (IOException ex) {
			ex.printStackTrace();
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}
}

Sau khi run

remote.server.port : 8080 remote.user : vuta remote.password : bimat remote.server : 192.168.1.100


All rights reserved

Viblo
Hãy đăng ký một tài khoản Viblo để nhận được nhiều bài viết thú vị hơn.
Đăng kí