Java 如何读取配置文件?
- 后端开发
- 2025-06-08
- 2900
在Java中获取配置文件主要通过以下方式:,1. 使用Properties类加载properties文件。,2. 通过ClassLoader的getResourceAsStream读取资源文件。,3. 利用ResourceBundle处理国际化配置文件。,4. Spring框架中可用@PropertySource或Environment接口。,5. 对于XML配置,常用SAX/DOM解析器处理。
基础方法:Properties类(.properties文件)
适用场景:键值对配置(数据库连接、路径设置等)
import java.io.InputStream;
import java.util.Properties;
public class PropertiesDemo {
public static void main(String[] args) {
Properties prop = new Properties();
try (InputStream input = PropertiesDemo.class
.getClassLoader()
.getResourceAsStream("config.properties")) {
if (input == null) {
System.err.println("配置文件未找到!");
return;
}
prop.load(input); // 加载配置文件
System.out.println("数据库URL: " + prop.getProperty("db.url"));
System.out.println("用户名: " + prop.getProperty("db.user"));
} catch (Exception e) {
e.printStackTrace();
}
}
}
配置文件示例 (src/main/resources/config.properties):
# 数据库配置 db.url = jdbc:mysql://localhost:3306/mydb db.user = root db.password = 123456
国际化支持:ResourceBundle类
适用场景:多语言资源配置
import java.util.Locale;
import java.util.ResourceBundle;
public class I18nDemo {
public static void main(String[] args) {
// 加载中文资源(文件名为messages_zh_CN.properties)
ResourceBundle bundle = ResourceBundle.getBundle("messages", Locale.SIMPLIFIED_CHINESE);
System.out.println("欢迎语: " + bundle.getString("welcome.message"));
}
}
文件结构:
resources/
├── messages_en_US.properties
└── messages_zh_CN.properties
XML配置:DOM解析器
适用场景:复杂层级配置
import org.w3c.dom.Document;
import javax.xml.parsers.DocumentBuilderFactory;
import java.io.File;
public class XmlConfigDemo {
public static void main(String[] args) throws Exception {
File file = new File("app-config.xml");
Document doc = DocumentBuilderFactory.newInstance()
.newDocumentBuilder()
.parse(file);
String host = doc.getElementsByTagName("host")
.item(0)
.getTextContent();
System.out.println("服务地址: " + host);
}
}
XML文件示例 (app-config.xml):

<config>
<server>
<host>api.example.com</host>
<port>8080</port>
</server>
</config>
现代方案:Java NIO文件API
适用场景:非标准路径文件读取
import java.nio.file.Files;
import java.nio.file.Paths;
public class NioFileReader {
public static void main(String[] args) throws Exception {
String content = new String(
Files.readAllBytes(Paths.get("/etc/myapp/custom.conf"))
);
System.out.println("配置内容: n" + content);
}
}
企业级方案:Spring Boot配置管理
依赖:spring-boot-starter
YAML配置 (application.yml):
cloud:
aws:
credentials:
access-key: AKIAEXAMPLE
secret-key: secret
注入配置:
@Value("${cloud.aws.credentials.access-key}")
private String accessKey; // 自动注入配置值
第三方库:Apache Commons Configuration
依赖(Maven):
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-configuration2</artifactId>
<version>2.8.0</version>
</dependency>
示例代码:

import org.apache.commons.configuration2.PropertiesConfiguration;
import org.apache.commons.configuration2.builder.fluent.Configurations;
public class ApacheConfigDemo {
public static void main(String[] args) throws Exception {
Configurations configs = new Configurations();
PropertiesConfiguration config = configs.properties("config.properties");
System.out.println("超时设置: " + config.getInt("timeout"));
}
}
最佳实践总结
-
路径处理
- 类路径文件:
ClassLoader.getResourceAsStream("file") - 绝对路径:
Paths.get("/abs/path") - 相对路径:
new File("conf/app.conf")
- 类路径文件:
-
安全建议
// 禁止加载外部路径防止路径遍历攻击 if (path.contains("..")) throw new SecurityException("非规路径!"); -
配置类型选型指南
| 文件类型 | 适用场景 | 工具推荐 |
|—————-|————————-|———————|
| .properties | 简单键值对 |Properties类 |
| .yaml/.yml | 层级化配置 | Spring Boot |
| .xml | 复杂结构化数据 | DOM/SAX解析器 |
| .json | REST服务配置 | GSON/Jackson | -
高并发场景
- 使用
static final缓存配置对象 - Spring Boot的
@ConfigurationProperties实现热加载
- 使用
常见问题解答
Q1:配置文件放在jar包外如何读取?

// 示例:读取jar同目录下的conf.properties
String externalPath = System.getProperty("user.dir") + "/conf.properties";
Properties prop = new Properties();
prop.load(new FileInputStream(externalPath));
Q2:如何实现配置热更新?
- 方案1:Apache Commons Configuration的
ReloadingFileBasedConfiguration - 方案2:Spring Cloud Config Server集中化管理
引用说明:本文代码示例遵循Java标准库规范,第三方库引用自Apache Commons官方文档及Spring Framework参考指南,实践建议基于Oracle官方安全标准和行业生产环境经验总结。
通过本文介绍的六种核心方法,您可灵活应对不同场景下的配置管理需求,建议根据项目规模选择方案——小型项目用Properties类足够,分布式系统推荐Spring Cloud Config等专业解决方案。
