惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Apple Machine Learning Research
Apple Machine Learning Research
M
MIT News - Artificial intelligence
罗磊的独立博客
博客园 - 【当耐特】
A
About on SuperTechFans
Last Week in AI
Last Week in AI
雷峰网
雷峰网
IT之家
IT之家
aimingoo的专栏
aimingoo的专栏
H
Hackread – Cybersecurity News, Data Breaches, AI and More
博客园_首页
博客园 - 叶小钗
Microsoft Azure Blog
Microsoft Azure Blog
博客园 - Franky
J
Java Code Geeks
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
D
Docker
Engineering at Meta
Engineering at Meta
B
Blog RSS Feed
The Cloudflare Blog
大猫的无限游戏
大猫的无限游戏
阮一峰的网络日志
阮一峰的网络日志
S
SegmentFault 最新的问题
Recent Announcements
Recent Announcements

博客园 - 火军刀

Vue3写法 创建测试表专用语句 基于Junit5的MockMvc单元测试基础方法 在指定目录下搜索文件名包含"项目"二字的Excel文件 启动Redis报错: # QForkMasterInit: system error caught. error code=0x00000070, message=CreateFileMapping failed.: no space on device eclipse为什么不允许查看包文件所在的目录? Hutool怎样指定日志工具 No matching distribution found for volcenginesdkarkruntime 如果你的idea右侧边栏和下边栏消失不见,没有了,不要惊慌 IDEA中使用腾讯云代码助手CodeBuddy 找到多个名为spring_web的片段 控制反转的通俗理解 Spring的pom.xml中的依赖 如果你的uniapp连不上手机 ollama可以不装在C盘,ollama安装时怎么选择路径? deepseek和千问是什么关系?DeepSeek-R1-Distill-Qwen-7B,这个模型中的deepseek和qwen是什么关系? 10种Java从数据库中取出数据的完整过程 用DOS命令删除子目录中所有文件名中包含“(1)”的文件 log4j.properties
properties对象
火军刀 · 2025-02-22 · via 博客园 - 火军刀

在 Java 编程中,java.util.Properties 是一个专门用于处理键值对配置文件的类,它继承自 Hashtable<Object,Object>,但强制要求键值对均为字符串类型(实际是 Hashtable<String,String>)。以下是其核心特性和使用场景:


一、核心特性

  1. 键值对存储

    • key=value 格式存储数据(类似 .ini.properties 文件)
    • 示例:user.name=Johndatabase.port=3306
  2. 文件 IO 支持

    • 可直接通过 load() 方法从输入流(如文件、网络资源)加载配置
    • 通过 store() 方法将配置持久化到文件
    // 加载配置文件
    try (InputStream input = new FileInputStream("config.properties")) {
        Properties prop = new Properties();
        prop.load(input);
    }
    
    // 保存配置文件
    try (OutputStream output = new FileOutputStream("config.properties")) {
        prop.store(output, "Database configuration");
    }
    
  3. 编码处理

    • 默认使用 ISO 8859-1 编码(可能需注意中文乱码问题)
    • 推荐使用 load(Reader)/store(Writer) 方法指定编码:
    prop.load(new InputStreamReader(input, "UTF-8"));
    
  4. 层次化访问

    • 支持通过 Properties 对象链式继承(defaults 属性)
    Properties defaults = new Properties();
    defaults.setProperty("timeout", "30");
    Properties prop = new Properties(defaults); // 继承默认值
    

二、典型应用场景

  1. 配置文件管理

    • 管理数据库连接参数、API 密钥、日志级别等
    • 示例 config.properties
      # Database settings
      db.url=jdbc:mysql://localhost:3306/mydb
      db.user=root
      db.password=secret
      
  2. 国际化支持

    • 加载不同语言资源文件(如 messages_en.propertiesmessages_zh.properties
  3. 系统属性扩展

    • System.getProperties() 配合使用,扩展 JVM 参数

三、注意事项

  1. 线程安全

    • 由于继承自 HashtableProperties 是线程安全的,但频繁同步可能影响性能
  2. 资源释放

    • 必须显式关闭 InputStream/OutputStream(推荐 try-with-resources)
  3. 类型局限

    • 仅支持字符串类型,复杂数据类型需手动转换:
    int timeout = Integer.parseInt(prop.getProperty("timeout"));
    
  4. 替代方案

    • XML 配置:更结构化,但解析复杂
    • YAML/JSON:层次化数据友好(需第三方库如 Jackson、SnakeYAML)
    • 环境变量:适用于容器化部署(如 Docker)

四、代码示例

// 读取配置
Properties prop = new Properties();
try (InputStream input = getClass().getClassLoader().getResourceAsStream("app.properties")) {
    prop.load(input);
    String dbUrl = prop.getProperty("db.url");
    String dbUser = prop.getProperty("db.user", "admin"); // 带默认值
} catch (IOException ex) {
    ex.printStackTrace();
}

// 动态修改配置
prop.setProperty("cache.enabled", "true");
try (OutputStream output = new FileOutputStream("app.properties")) {
    prop.store(output, "Updated cache settings");
}

五、替代工具推荐

场景 推荐工具 优势
复杂层级配置 Apache Commons Configuration 支持 XML、JSON、INI 等多种格式
云原生配置 Spring Cloud Config 集中化管理,动态刷新
高性能键值存储 Redis 内存数据库,支持分布式

Properties 是 Java 生态中轻量级配置管理的基石,适合简单场景,但在复杂工程中建议结合具体需求选择更专业的配置管理方案。