在Java中,Properties类是用于处理键值对的配置文件的常用类。它继承自Hashtable类,其中的键和值都是字符串类型。下面是Properties类的一些常用方法:
- 向Properties对象中添加一个键值对。
Properties prop = new Properties(); prop.setProperty("key1", "value1");
- 获取指定键对应的值。
String value = prop.getProperty("key1");
- 获取指定键对应的值,如果键不存在,则返回defaultValue。
String value = prop.getProperty("key2", "default");
- 从输入流中加载属性列表。
InputStream input = new FileInputStream("config.properties"); prop.load(input);
- 将Properties对象中的属性列表存储到输出流中。
OutputStream output = new FileOutputStream("config.properties"); prop.store(output, "This is a comment");
- 获取所有键的枚举。
while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); String value = prop.getProperty(key); System.out.println(key + " = " + value); }