首页 > 编程笔记 > Java笔记 阅读:5

Java Properties类的用法(附带实例)

Java 中的 Properties 类是一个比较特殊的集合,它表示一个持久的属性集,在属性列表中的每个 key(键)及其对应的 value(值)都是一个字符串。

Properties 类主要用于读取 Java 的配置文件,其配置文件常为 .properties 文件,属文本文件,是以键值对的形式进行参数配置的。

Properties 类的常用方法及其说明如下表所示:

表:Properties类的常用方法及其说明
方法 功能描述
String getProperty(String key) 用指定的键在此属性列表中搜索属性
void load(InputStream inStream) throws IOException 将文件中的键值对加载到 properties 集合中
Object setProperty(String key, String value) 调用 Hashtable 的方法 put()
void store(Writer writer, String comments) 将集合中的数据存储到 .properties 文件中

例如,创建一个 preperties 集合,向该集合中分别添加如下的键值对:连接 MySQL 数据库的驱动、连接 MySQL 数据库的用户名和连接 MySQL 数据库的密码。使用 getProperty() 方法分别获取连接 MySQL 数据库的驱动、用户名和密码,并输出到控制台上。代码如下:
import java.util.Properties;

public class Test {
    public static void main(String[] args) {
        // 创建 properties 集合
        Properties pro = new Properties();
        // 向集合中存储数据
        pro.put("driver", "com.mysql.jdbc.driver");
        pro.put("username", "root");
        pro.put("password", "123456");
        // 取数据
        String v1 = pro.getProperty("driver");
        String v2 = pro.getProperty("username");
        String v3 = pro.getProperty("password");
        // 输出数据
        System.out.println(v1);
        System.out.println(v2);
        System.out.println(v3);
    }
}
运行结果如下:

com.mysql.jdbc.driver
root
123456


再例如,创建一个 preperties 集合,向 preperties 集合中分别添加以下键值对:name 及其值 David、age 及其值 26。使用 store() 方法将 preperties 集合中的键值对存储到当前项目文件夹下的 pro.propreties 文件中。代码如下:
import java.io.FileOutputStream;
import java.util.Properties;

public class Test {
    public static void main(String[] args) {
        // 创建 properties 集合
        Properties pro = new Properties();
        pro.put("name", "David");
        pro.put("age", "26");
        // 明确 pro.properties 文件的路径
        try (FileOutputStream fos = new FileOutputStream("pro.properties")) {
            // 将集合中的数据存储到 properties 文件中
            pro.store(fos, "this is a person");    // properties 文件中不可以存储中文
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
找到并打开 pro.propreties 文件后,即可看到程序的运行结果:

#this is a person
#Sun Dec 02 16:14:51 CST 2025
name=David
age=26

相关文章