什么是 Properties 文件?
Properties 文件是 Java 中一种常用的配置文件格式,它本质上是一个文本文件,以 键=值 的形式存储数据。

主要特点:
- 键值对存储:每行定义一个键值对,用等号 或冒号 分隔(推荐使用等号)。
- 注释:以 或 开头的行被视为注释。
- 编码:传统的 Properties 文件使用 ISO-8859-1 (Latin-1) 编码,这意味着它不能直接存储非 ASCII 字符(如中文)。
- 转义:如果值中包含空格、等号 、冒号 或换行符等特殊字符,需要进行转义,或者使用反斜杠
\将值跨行连接。 - 扩展名:通常使用
.properties作为文件扩展名。
一个简单的示例
创建一个名为 config.properties 的文件,内容如下:
# config.properties # 这是一个配置文件 # 数据库配置 db.url=jdbc:mysql://localhost:3306/mydb db.username=root db.password=secret_password db.pool.size=10 # 应用配置 app.name=我的第一个Java应用 app.version=1.0.0 app.debug=true
如何在 Java 中读取 Properties 文件?
Java 提供了 java.util.Properties 类来处理 .properties 文件,主要有两种加载方式:从类路径加载和从文件系统加载。
从类路径 加载 (推荐)
这种方式最常用,尤其是在打包成 JAR 或 WAR 文件后,它将配置文件放在 src/main/resources 目录下,Maven/Gradle 会自动将其放到类路径的根目录中。

代码示例:
import java.io.InputStream;
import java.util.Properties;
public class PropertiesFromClasspathExample {
public static void main(String[] args) {
// 1. 创建 Properties 对象
Properties props = new Properties();
try {
// 2. 从类路径加载文件
// 使用 ClassLoader.getResourceAsStream() 方法
// 文件路径相对于 classpath 的根目录
InputStream input = PropertiesFromClasspathExample.class.getClassLoader()
.getResourceAsStream("config.properties");
if (input == null) {
System.out.println("抱歉,无法找到 config.properties");
return;
}
// 3. 加载输入流
props.load(input);
// 4. 获取属性值
String dbUrl = props.getProperty("db.url");
String username = props.getProperty("db.username");
String password = props.getProperty("db.password");
String appName = props.getProperty("app.name");
String appVersion = props.getProperty("app.version");
boolean isDebug = Boolean.parseBoolean(props.getProperty("app.debug"));
// 打印结果
System.out.println("应用名称: " + appName);
System.out.println("应用版本: " + appVersion);
System.out.println("数据库URL: " + dbUrl);
System.out.println("用户名: " + username);
System.out.println("密码: " + password);
System.out.println("调试模式: " + isDebug);
// 5. 关闭输入流
input.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
从文件系统 加载
如果你知道配置文件在本地磁盘上的确切路径,可以使用这种方式。
代码示例:
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertiesFromFileSystemExample {
public static void main(String[] args) {
Properties props = new Properties();
// 请将此路径更改为你的实际文件路径
String filePath = "C:/projects/myapp/config/config.properties";
try (InputStream input = new FileInputStream(filePath)) {
props.load(input);
// ... 获取和打印属性值的代码同上 ...
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
注意:使用
try-with-resources语句可以自动关闭InputStream,是推荐的做法。(图片来源网络,侵删)
如何处理中文等非 ASCII 字符?
如前所述,.properties 文件默认使用 ISO-8859-1 编码,直接写入中文会乱码。
解决方案一:在 Java 代码中进行转义
这是最传统的方法,将中文字符用 Unicode 转义序列表示。
app.name=我的应用 需要写成:
app.name=\u6211\u7684\u5e94\u7528
然后在 Java 中读取时,Properties 类会自动将其转换回正确的字符。
解决方案二:使用 Java 9+ 的 java.util.Properties#load(Reader)
从 Java 9 开始,Properties 类新增了可以接受 Reader 对象的 load 方法,这样我们就可以在 Java 代码中指定文件的编码(如 UTF-8)。
代码示例 (Java 9+):
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.Properties;
public class PropertiesWithUTF8Example {
public static void main(String[] args) {
Properties props = new Properties();
// 文件内容可以直接写中文,但必须确保文件本身是UTF-8编码保存的
// app.name=我的第一个Java应用
try (Reader reader = new InputStreamReader(
PropertiesWithUTF8Example.class.getClassLoader()
.getResourceAsStream("config_utf8.properties"),
StandardCharsets.UTF_8)) {
if (reader == null) {
System.out.println("抱歉,无法找到 config_utf8.properties");
return;
}
// 使用 load(Reader) 方法,并指定UTF-8编码
props.load(reader);
String appName = props.getProperty("app.name");
System.out.println("应用名称: " + appName); // 正确输出: 我的第一個Java應用
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
前提:你的 config_utf8.properties 文件必须使用 UTF-8 编码格式保存。
如何写入 Properties 文件?
同样,使用 Properties 类的 store() 方法。
代码示例:
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Properties;
public class WritePropertiesExample {
public static void main(String[] args) {
Properties props = new Properties();
props.setProperty("server.port", "8080");
props.setProperty("logging.level", "INFO");
props.setProperty("welcome.message", "Hello, World!");
// 输出到文件
try (OutputStream output = new FileOutputStream("output.properties")) {
// 将 Properties 对象写入到输出流
// 参数:输出流、注释(写入到文件第一行)
props.store(output, "这是由程序自动生成的配置文件");
System.out.println("配置文件已成功生成: output.properties");
} catch (IOException io) {
io.printStackTrace();
}
}
}
生成的 output.properties 文件内容如下(注意,store 方法会进行一些格式化和排序):
# 这是由程序自动生成的配置文件 #Mon Nov 20 10:30:00 CST 2025 logging.level=INFO server.port=8080 welcome.message=Hello, World!
最佳实践
- 使用类路径:对于大多数应用,将配置文件放在
src/main/resources目录下并通过ClassLoader加载是最佳实践,因为它使应用更具可移植性。 - 提供默认值:使用
getProperty(String key, String defaultValue)方法,当某个配置项不存在时,可以返回一个默认值,避免NullPointerException。String dbUrl = props.getProperty("db.url", "jdbc:default:database"); // db.url 不存在,则使用默认值 - 处理编码:如果配置文件中包含中文或其他非 ASCII 字符,强烈建议使用 Java 9+ 的
load(Reader)方法,并确保文件以 UTF-8 编码保存,这是最现代、最方便的解决方案。 - 敏感信息:永远不要将密码、API密钥等敏感信息直接明文写在 Properties 文件中,应考虑使用环境变量、专门的密钥管理服务(如 HashiCorp Vault、AWS Secrets Manager)或加密配置文件的方式。
- 使用日志框架:在实际项目中,通常使用 Log4j, Logback 等日志框架来管理配置,而不是直接用
System.out.println,这些框架本身也支持通过 Properties 文件进行配置。
| 特性/操作 | 描述 |
|---|---|
| 核心类 | java.util.Properties |
| 文件格式 | 键=值, 或 注释 |
| 加载方式 | props.load(InputStream) (类路径) 或 props.load(Reader) (指定编码) |
| 编码问题 | 传统方式需 Unicode 转义;Java 9+ 推荐使用 load(Reader) + UTF-8 |
| 获取值 | props.getProperty("key") |
| 写入文件 | props.store(OutputStream, comments) |
| 最佳实践 | 放在 resources 目录、提供默认值、妥善处理敏感信息和编码 |

