java.util.Properties
时间: 2024-03-22 19:18:03 浏览: 9
java.util.Properties 是一个用于处理属性文件的类,它继承自 Hashtable 类。它可以将属性文件中的键值对加载到内存中,并提供了一系列的读写操作方法,可以方便地获取或设置属性值。Properties 类常用于读取配置文件,如数据库连接配置等。
该类的常用方法包括:
- load(InputStream inStream):从输入流中读取属性列表(键和元素对)。
- getProperty(String key):用指定的键在此属性列表中搜索属性。
- setProperty(String key, String value):设置属性值,如果该属性已经存在则更新该属性的值。
- store(OutputStream out, String comments):将此 Properties 表中的属性列表(键和元素对)写入输出流。
示例代码:
```java
// 读取属性文件
Properties prop = new Properties();
InputStream in = new FileInputStream("config.properties");
prop.load(in);
// 获取属性值
String dbUrl = prop.getProperty("db.url");
String dbUser = prop.getProperty("db.username");
String dbPassword = prop.getProperty("db.password");
// 设置属性值
prop.setProperty("db.url", "jdbc:mysql://localhost:3306/mydb");
// 写入属性文件
OutputStream out = new FileOutputStream("config.properties");
prop.store(out, "Database Configurations");
```