Java的java.util.Properties
类是用于处理属性文件的工具类,它继承自java.util.Hashtable
类。Properties
类提供了读取和写入属性文件的方法,使得我们能够在程序中轻松地操作和管理配置信息。下面是对Properties
类的API进行讲解,并包含四个案例来演示其用法。
1. 加载和保存属性文件
void load(InputStream inStream) throws IOException
:从输入流中加载属性文件。void store(OutputStream out, String comments) throws IOException
:将属性文件保存到输出流中。
案例1:加载属性文件
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertiesExample1 {
public static void main(String[] args) {
try {
Properties properties = new Properties();
FileInputStream fis = new FileInputStream("config.properties");
properties.load(fis);
String username = properties.getProperty("username");
String password = properties.getProperty("password");
System.out.println("Username: " + username);
System.out.println("Password: " + password);
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
案例2:保存属性文件
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class PropertiesExample2 {
public static void main(String[] args) {
try {
Properties properties = new Properties();
properties.setProperty("username", "john");
properties.setProperty("password", "secret");
FileOutputStream fos = new FileOutputStream("config.properties");
properties.store(fos, "Application Configuration");
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. 获取和设置属性值
String getProperty(String key)
:根据键获取属性值。String getProperty(String key, String defaultValue)
:根据键获取属性值,如果键不存在,则返回默认值。void setProperty(String key, String value)
:设置属性值。
案例3:获取和设置属性值
import java.util.Properties;
public class PropertiesExample3 {
public static void main(String[] args) {
Properties properties = new Properties();
properties.setProperty("database", "mysql");
properties.setProperty("username", "admin");
String database = properties.getProperty("database");
String password = properties.getProperty("password", "default");
System.out.println("Database: " + database);
System.out.println("Password: " + password);
}
}
3. 遍历属性
Enumeration<?> propertyNames()
:返回属性的枚举。Set<String> stringPropertyNames()
:返回属性的键集合。
案例4:遍历属性
import java.util.Properties;
import java.util.Set;
public class PropertiesExample4 {
public static void main(String[] args) {
Properties properties = new Properties();
properties.setProperty("database", "mysql");
properties.setProperty("username", "admin");
properties.setProperty("password", "secret");
Set<String> keys = properties.stringPropertyNames();
for (String key : keys) {
String value = properties.getProperty(key);
System.out.println(key + ": " + value);
}
}
}
以上是对java.util.Properties
类的主要API进行的讲解,并提供了四个案例来