Properties类用于读写.properties配置文件,支持键值对存储,常用load()读取、store()写入,适合Java项目配置管理。

在Java开发中,Properties 类是处理配置文件最常用的方式之一。它继承自 Hashtable,专门用于读取和保存键值对形式的配置信息,通常配合 .properties 文件使用。这类文件常用于存储数据库连接、应用参数、国际化资源等。
使用 Properties 读取配置文件是其最常见的用途。一般通过 load() 方法从输入流加载属性。
假设项目根目录下有一个名为 config.properties 的文件,内容如下:
app.name=MyApplication app.version=1.0.0 db.url=jdbc:mysql://localhost:3306/test db.user=root db.password=123456
可以通过以下代码读取这些配置:
立即学习“Java免费学习笔记(深入)”;
示例代码:
import java.io.*;
import java.util.Properties;
public class ReadConfig {
public static void main(String[] args) {
Properties prop = new Properties();
try (InputStream input = ReadConfig.class.getClassLoader().getResourceAsStream("config.properties")) {
if (input == null) {
System.out.println("无法找到配置文件");
return;
}
prop.load(input);
System.out.println("应用名称: " + prop.getProperty("app.name"));
System.out.println("数据库URL: " + prop.getProperty("db.url"));
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
注意:使用 getClassLoader().getResourceAsStream() 可以从类路径下加载文件,适用于打包成 JAR 后的场景。
除了读取,Properties 还支持将当前属性写入文件,使用 store() 方法即可。
这在运行时需要动态修改配置并持久化时非常有用。
示例:创建一个新的配置并保存到本地文件
import java.io.*;
import java.util.Properties;
public class SaveConfig {
public static void main(String[] args) {
Properties prop = new Properties();
prop.setProperty("server.host", "192.168.1.100");
prop.setProperty("server.port", "8080");
prop.setProperty("debug", "true");
try (OutputStream output = new FileOutputStream("output-config.properties")) {
prop.store(output, "Generated configuration file");
System.out.println("配置已保存");
} catch (IOException e) {
e.printStackTrace();
}
}
}
执行后会生成 output-config.properties 文件,内容包含键值对及你指定的注释。
如果配置文件不在类路径中,而是放在某个具体路径(如项目外部),可以使用 FileInputStream 直接读取。
例如读取项目根目录下的 config.properties:
try (FileInputStream fis = new FileInputStream("config.properties")) {
prop.load(fis);
} catch (IOException e) {
e.printStackTrace();
}
这种方式适合需要用户自定义配置文件路径的场景。
使用 Properties 时有几个关键点需要注意:
基本上就这些。Properties 简单易用,适合中小型项目的配置管理,掌握它的读写操作对日常开发很有帮助。
以上就是在Java中如何使用Properties读取和保存配置文件_Properties类操作指南的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号