Java读取配置文件最常用三种方法:1.Properties类适用于简单键值对,通过InputStream加载classpath下.properties文件;2.ResourceBundle支持多语言,按Locale自动匹配messages_zh_CN等文件;3.Spring Boot推荐@Value和Environment,支持yml/properties/环境变量统一管理并自动类型转换。

Java 读取配置文件最常用、最简明的三种方法是:使用 Properties 类(.properties 文件)、使用 ResourceBundle(支持国际化)、使用第三方库如 Apache Commons Configuration 或 Spring 的 @Value / Environment(适合现代项目)。下面直接说清楚每种怎么用、适用场景和关键细节。
适合简单键值对配置,比如数据库地址、开关标志等。文件内容示例:
db.url=jdbc:mysql://localhost:3306/myapp
debug=true
代码示例:
InputStream 加载 classpath 下的文件(推荐):Properties props = new Properties();
try (InputStream is = MyClass.class.getResourceAsStream("/config.properties")) {
props.load(is);
String url = props.getProperty("db.url");
boolean debug = Boolean.parseBoolean(props.getProperty("debug"));
}/ 开头表示从 classpath 根开始;不加斜杠是相对当前类路径适合需要中英文切换的配置,比如提示文案、页面标题等。文件命名需带语言代码,如:
messages.properties
messages_zh_CN.properties
messages_en_US.properties
立即学习“Java免费学习笔记(深入)”;
代码示例:
ResourceBundle bundle = ResourceBundle.getBundle("messages", Locale.getDefault());
String welcome = bundle.getString("welcome.message"); // 读取键 welcome.messagemessages.properties,找不到再按 locale 找对应变体如果你用的是 Spring Boot,这是最自然、最灵活的方式,支持 yml、properties、环境变量、命令行参数统一管理。
app: name: MyApp timeout: 3000
@Value 注入单个值:@Value("${app.timeout:5000}") // 冒号后是默认值
private long timeout;Environment 获取任意配置(适合动态键名):@Autowired
private Environment env;
<p>String name = env.getProperty("app.name", "DefaultApp");基本上就这些。小项目用 Properties 足够;要国际化选 ResourceBundle;Spring 项目优先用 @Value + Environment —— 清晰、安全、可维护。
以上就是Java 怎么读取配置文件?三种简明方法的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号