Java中用Properties.load()读取.properties文件需用InputStream或Reader(推荐UTF-8编码),通过ClassLoader.getResourceAsStream()加载类路径资源,用getProperty()安全获取字符串值并支持默认值。

Java 中通过 Properties.load() 读取 .properties 文件是最基础且常用的配置加载方式,核心是用 InputStream 打开文件并交给 Properties 实例解析。
确保 properties 文件格式正确
.properties 文件需满足标准格式:每行一个键值对,用 = 或 : 分隔,支持 Unicode 转义(如 \u4f60\u597d),注释以 # 或 ! 开头。空行和纯注释行会被忽略。
示例 config.properties:
app.name=MyApp db.url=jdbc:mysql://localhost:3306/test log.level=INFO user.name=\u5F20\u4E09
使用 ClassLoader 加载类路径下的文件
推荐方式:把 .properties 放在 src/main/resources(Maven/Gradle 项目)下,用 ClassLoader.getResourceAsStream() 获取流,避免硬编码路径或文件不存在异常。
立即学习“Java免费学习笔记(深入)”;
- 文件在类路径根目录(如
resources/config.properties):
Properties props = new Properties();
try (InputStream is = getClass().getClassLoader().getResourceAsStream("config.properties")) {
if (is == null) {
throw new RuntimeException("config.properties not found in classpath");
}
props.load(is);
} catch (IOException e) {
throw new RuntimeException("Failed to load config.properties", e);
}
- 若文件在子目录(如
resources/conf/app.properties),路径写"conf/app.properties"
读取后安全获取值
Properties 继承自 Hashtable,但建议用 getProperty(key) 而非 get(key),因为前者返回 String,后者返回 Object;同时可指定默认值防 null。
- 直接获取(可能为 null):
String name = props.getProperty("app.name"); - 带默认值(更健壮):
String level = props.getProperty("log.level", "WARN"); - 转为其他类型需自行解析,例如:
int port = Integer.parseInt(props.getProperty("server.port", "8080"));(注意捕获NumberFormatException)
注意字符编码问题
Properties.load(InputStream) 默认按 ISO-8859-1 解码,中文会乱码。若文件保存为 UTF-8(推荐),应改用 load(Reader) 配合 InputStreamReader 指定编码:
try (InputStream is = getClass().getClassLoader().getResourceAsStream("config.properties");
Reader reader = new InputStreamReader(is, StandardCharsets.UTF_8)) {
props.load(reader);
}
或者提前将 UTF-8 文件中的中文转为 Unicode 转义(如用 native2ascii 工具),这样仍可用 load(InputStream)。


















