• 【Java 基础篇】Properties 结合集合类的使用详解


    在这里插入图片描述

    Java 中的 Properties 类是一个常见的用于管理配置信息的工具,它可以被看作是一种键值对的集合。虽然 Properties 通常用于处理配置文件,但它实际上也可以作为通用的 Map 集合来使用。在本文中,我们将详细探讨如何使用 Properties 作为 Map 集合,以及它的一些常见用法。

    什么是 Properties?

    Properties 是 Java 核心库中的一个类,它继承自 Hashtable,主要用于管理键值对形式的配置信息。这些键值对被存储在一个 .properties 文件中,通常采用以下格式:

    key1=value1
    key2=value2
    key3=value3
    
    • 1
    • 2
    • 3

    在配置文件中,键名和对应的值之间用等号(或冒号)分隔。每个键值对通常表示一个配置项。

    Properties 作为 Map 集合的基本用法

    创建 Properties 对象

    首先,让我们看看如何创建和初始化一个 Properties 对象作为 Map 集合使用:

    Properties properties = new Properties();
    
    • 1

    添加键值对

    可以使用 setProperty 方法添加键值对,就像操作普通的 Map 一样:

    properties.setProperty("name", "John");
    properties.setProperty("age", "30");
    
    • 1
    • 2

    获取值

    要获取某个键的值,可以使用 getProperty 方法:

    String name = properties.getProperty("name");
    String age = properties.getProperty("age");
    
    • 1
    • 2

    遍历键值对

    可以使用 entrySet 方法遍历 Properties 中的所有键值对:

    for (Map.Entry<Object, Object> entry : properties.entrySet()) {
        String key = (String) entry.getKey();
        String value = (String) entry.getValue();
        System.out.println(key + ": " + value);
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    移除键值对

    如果需要移除某个键值对,可以使用 remove 方法:

    properties.remove("age");
    
    • 1

    Properties 的高级用法

    从文件加载配置

    Properties 还可以从外部配置文件加载配置信息。假设有一个名为 config.properties 的配置文件:

    db.url=jdbc:mysql://localhost:3306/mydb
    db.username=admin
    db.password=secret
    
    • 1
    • 2
    • 3

    您可以使用以下方式加载配置信息:

    try (FileInputStream fileInputStream = new FileInputStream("config.properties")) {
        properties.load(fileInputStream);
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    将 Properties 写入文件

    您还可以将 Properties 对象中的配置信息写入到文件中:

    try (FileOutputStream fileOutputStream = new FileOutputStream("config.properties")) {
        properties.store(fileOutputStream, "Database Configuration");
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5

    默认值

    Properties 允许您为配置项设置默认值。如果某个配置项不存在,将返回默认值:

    String dbUrl = properties.getProperty("db.url", "jdbc:mysql://localhost:3306/defaultdb");
    
    • 1

    使用 Properties 默认值

    Java 提供了一个便捷的方法来获取系统级配置,该配置是 Properties 的默认值。您可以使用 System.getProperties() 来获取系统级配置,并将其视为 Properties 对象:

    Properties systemProperties = System.getProperties();
    String javaVersion = systemProperties.getProperty("java.version");
    
    • 1
    • 2

    Properties 作为通用的 Map 集合

    尽管 Properties 主要用于配置文件,但它实际上是一个通用的 Map 集合,因此也可以用于其他用途。以下是一些示例用法:

    存储和检索自定义对象

    您可以使用 Properties 存储和检索自定义对象。需要将自定义对象序列化为字符串,然后存储它们:

    Person person = new Person("Alice", 25);
    String serializedPerson = serializePerson(person);
    properties.setProperty("person", serializedPerson);
    
    • 1
    • 2
    • 3

    然后,您可以获取并反序列化该对象:

    String serializedPerson = properties.getProperty("person");
    Person person = deserializePerson
    
    (serializedPerson);
    
    • 1
    • 2
    • 3
    • 4

    用于缓存

    Properties 可以用作简单的缓存,将数据存储在内存中以提高访问速度:

    // 存储数据到缓存
    properties.setProperty("cacheKey", "cachedValue");
    
    // 从缓存中获取数据
    String cachedValue = properties.getProperty("cacheKey");
    
    • 1
    • 2
    • 3
    • 4
    • 5

    用于国际化

    在国际化应用程序中,Properties 可用于存储本地化资源的键值对:

    properties.setProperty("welcome.message", "Welcome to our application!");
    properties.setProperty("error.message", "An error occurred.");
    
    • 1
    • 2

    然后,根据用户的本地化设置,可以获取相应的消息。

    实例总结

    创建 Properties 对象

    要使用 Properties,首先需要创建一个 Properties 对象,然后加载配置文件。下面是创建 Properties 对象并加载配置文件的示例:

    import java.io.FileInputStream;
    import java.io.IOException;
    import java.util.Properties;
    
    public class ConfigLoader {
        public static Properties loadConfig(String filePath) {
            Properties properties = new Properties();
            try {
                FileInputStream fileInputStream = new FileInputStream(filePath);
                properties.load(fileInputStream);
                fileInputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return properties;
        }
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17

    读取配置项

    一旦配置文件加载到 Properties 对象中,您可以使用 getProperty 方法来获取特定配置项的值。例如:

    Properties config = ConfigLoader.loadConfig("app.properties");
    String dbUrl = config.getProperty("db.url");
    String dbUser = config.getProperty("db.username");
    String dbPassword = config.getProperty("db.password");
    
    • 1
    • 2
    • 3
    • 4

    修改配置项

    要修改配置项的值,可以使用 setProperty 方法。例如:

    config.setProperty("app.title", "My Awesome App");
    config.setProperty("app.version", "1.0");
    
    • 1
    • 2

    保存配置

    修改配置后,您可以使用 store 方法将更改后的配置保存回文件。例如:

    try {
        FileOutputStream fileOutputStream = new FileOutputStream("app.properties");
        config.store(fileOutputStream, "Updated App Configuration");
        fileOutputStream.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7

    使用 Properties 存储列表

    假设您需要配置一个邮件服务器的多个 SMTP 地址。可以使用逗号分隔的字符串将它们存储在 Properties 中:

    config.setProperty("mail.smtp.servers", "smtp1.example.com,smtp2.example.com,smtp3.example.com");
    
    • 1

    然后,您可以使用 split 方法将它们拆分为列表:

    String smtpServers = config.getProperty("mail.smtp.servers");
    List<String> smtpServerList = Arrays.asList(smtpServers.split(","));
    
    • 1
    • 2

    使用 Properties 存储映射

    如果您需要配置键值对的映射,也可以使用 Properties 来存储它们。例如,您可以配置数据库连接池的参数:

    config.setProperty("db.connection.pool.size", "10");
    config.setProperty("db.connection.timeout", "30000");
    
    • 1
    • 2

    然后,您可以使用 getProperty 方法将它们提取到映射中:

    int connectionPoolSize = Integer.parseInt(config.getProperty("db.connection.pool.size"));
    int connectionTimeout = Integer.parseInt(config.getProperty("db.connection.timeout"));
    
    Map<String, Integer> dbConfig = new HashMap<>();
    dbConfig.put("connectionPoolSize", connectionPoolSize);
    dbConfig.put("connectionTimeout", connectionTimeout);
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6

    使用 Properties 存储自定义对象

    有时,配置数据可能更复杂,需要存储

    自定义对象。在这种情况下,您可以将对象序列化为字符串,然后存储在 Properties 中。例如,假设您需要配置一个用户对象:

    User user = new User("john.doe", "John Doe", 30);
    String serializedUser = serializeUser(user);
    config.setProperty("user.data", serializedUser);
    
    • 1
    • 2
    • 3

    然后,您可以使用 getProperty 方法获取字符串,并将其反序列化为对象:

    String serializedUser = config.getProperty("user.data");
    User user = deserializeUser(serializedUser);
    
    • 1
    • 2

    总结

    Properties 是 Java 中处理配置文件的强大工具,它易于使用且适用于许多应用程序。通过结合使用 Properties 和集合类,您可以更灵活地管理和操作配置数据,以满足各种不同的需求。不过,在处理更复杂的配置数据时,请确保数据的一致性和安全性,以及适当的异常处理,以提高应用程序的稳定性和可维护性。

    希望本文对您理解如何使用 Properties 和集合类来管理配置文件有所帮助。

  • 相关阅读:
    离职单干后才明白怎么做好外贸
    Yakit单兵作战神器简单使用
    【Vue】内置指令真的很常用!
    终于知道Kafka为什么这么快了!
    pikachu靶场-upload-速通
    深度学习跨平台环境问题
    JavaScript知识点复习--(二)函数高级
    imx6ul链接地址、运行地址、加载地址、位置无关、mmu的关系
    Vue中props组件和slot标签的区别
    ARM接口编程—RTC(exynos 4412平台)
  • 原文地址:https://blog.csdn.net/qq_21484461/article/details/133050679