当前位置:首页 > Java

java如何使用properties

2026-03-23 17:29:33Java

使用 Properties 类加载和读取配置文件

在 Java 中,java.util.Properties 类用于处理键值对格式的配置文件(通常以 .properties 为后缀)。以下是基本使用方法:

创建 Properties 对象并加载文件

Properties prop = new Properties();
try (InputStream input = new FileInputStream("config.properties")) {
    prop.load(input);
} catch (IOException ex) {
    ex.printStackTrace();
}

读取属性值

String username = prop.getProperty("username");
String password = prop.getProperty("password", "defaultPassword"); // 带默认值

通过类加载器读取资源文件

当配置文件位于类路径(如 resources 目录)时,可以通过类加载器获取:

try (InputStream input = getClass().getClassLoader().getResourceAsStream("app.properties")) {
    prop.load(input);
} catch (IOException e) {
    e.printStackTrace();
}

写入 Properties 文件

将属性写入文件:

try (OutputStream output = new FileOutputStream("config.properties")) {
    prop.setProperty("db.url", "jdbc:mysql://localhost:3306/mydb");
    prop.store(output, "Database configuration");
} catch (IOException io) {
    io.printStackTrace();
}

处理中文编码

Properties 文件默认使用 ISO-8859-1 编码。如需处理中文,可使用 ResourceBundle 或转换为 Unicode 转义序列:

// 使用 ResourceBundle 读取中文(文件需为 UTF-8)
ResourceBundle bundle = ResourceBundle.getBundle("messages", new UTF8Control());
String value = bundle.getString("key");

// 自定义 UTF8Control 类需继承 ResourceBundle.Control

与 XML 格式交互

Properties 支持 XML 格式的读写:

// 从 XML 加载
prop.loadFromXML(new FileInputStream("config.xml"));

// 保存为 XML
prop.storeToXML(new FileOutputStream("config.xml"), "XML配置");

默认值链

通过继承实现默认值覆盖:

java如何使用properties

Properties defaults = new Properties();
defaults.setProperty("color", "red");

Properties props = new Properties(defaults);
String color = props.getProperty("color"); // 返回 "red"

注意事项

  • 文件路径区分绝对路径和类路径资源
  • 修改后的 Properties 需要显式调用 store() 保存
  • 生产环境建议使用配置管理工具(如 Spring Boot 的 @ConfigurationProperties

分享给朋友:

相关文章

react moment如何使用

react moment如何使用

安装 react-moment 通过 npm 或 yarn 安装 react-moment: npm install react-moment 或 yarn add react-moment 基本…

如何删除java

如何删除java

卸载 Java 的步骤 Windows 系统: 打开控制面板,选择“程序和功能”或“卸载程序”,在列表中找到 Java 相关条目(如“Java Runtime Environment”或“Java D…

java如何学习

java如何学习

学习Java的有效方法 理解基础概念 Java是一门面向对象的编程语言,掌握基础概念如变量、数据类型、运算符、控制语句(if-else、循环)是必要的。面向对象的核心概念包括类、对象、继承、多态和封装…

java如何react

java如何react

在Java中使用React 要在Java项目中集成React,通常需要将React前端与Java后端结合使用。以下是几种常见的方法: 使用Spring Boot作为后端 Spring Boot是一个…

如何使用ink react

如何使用ink react

安装 Ink 和 React 在项目目录下运行以下命令安装 Ink 和 React 的依赖: npm install ink react 创建基础组件 创建一个简单的 Ink 组件,例如 Hello…

如何运行java文件

如何运行java文件

运行Java文件的方法 确保已安装Java Development Kit (JDK),可通过命令行输入java -version和javac -version验证安装。 编写Java代码并保存为.…