Java 遍历 Properties 文件的方法
在 Java 中,Properties 类是 java.util 包中的一个类,用于处理属性文件(.properties 文件),以下是几种遍历 Properties 对象的方法:

方法1:使用 keySet() 和 for-each 循环
Properties props = new Properties();
// 加载属性文件...
// 方法1:遍历键
for (String key : props.stringPropertyNames()) {
String value = props.getProperty(key);
System.out.println(key + " = " + value);
}
方法2:使用 entrySet() 和 for-each 循环
Properties props = new Properties();
// 加载属性文件...
// 方法2:遍历键值对
for (Map.Entry<Object, Object> entry : props.entrySet()) {
String key = (String) entry.getKey();
String value = (String) entry.getValue();
System.out.println(key + " = " + value);
}
方法3:使用 Enumeration(传统方式)
Properties props = new Properties();
// 加载属性文件...
// 方法3:使用Enumeration(传统方式)
Enumeration<?> e = props.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
String value = props.getProperty(key);
System.out.println(key + " = " + value);
}
完整示例
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Map;
import java.util.Properties;
public class PropertiesTraversalExample {
public static void main(String[] args) {
Properties props = new Properties();
try (InputStream input = new FileInputStream("config.properties")) {
props.load(input);
} catch (IOException ex) {
ex.printStackTrace();
}
// 方法1:使用keySet()
System.out.println("方法1:使用keySet()");
for (String key : props.stringPropertyNames()) {
System.out.println(key + " = " + props.getProperty(key));
}
// 方法2:使用entrySet()
System.out.println("\n方法2:使用entrySet()");
for (Map.Entry<Object, Object> entry : props.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
// 方法3:使用Enumeration
System.out.println("\n方法3:使用Enumeration");
Enumeration<?> e = props.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
System.out.println(key + " = " + props.getProperty(key));
}
}
}
注意事项
stringPropertyNames()方法只返回字符串类型的键,比propertyNames()更安全- 如果属性文件包含非字符串的键或值,使用
entrySet()方法更合适 - 在遍历过程中修改
Properties对象可能会导致ConcurrentModificationException - 建议使用 try-with-resources 语句来关闭输入流
方法都可以有效地遍历 Properties 对象,选择哪种方法主要取决于你的具体需求和代码风格偏好。

