文章摘要
该文章介绍了如何通过Java的`Properties`类从文件中读取属性值。文章详细解释了两个主要方法:
1. `readValue(String filePath, String key)`:该方法从指定文件路径`filePath`中读取指定键`key`的属性值。通过使用`Properties.load(InputStream)`方法加载属性文件,然后直接通过`getProperty(key)`获取值。
2. `readProperties(String filePath)`:该方法读取整个属性文件的所有属性。它同样使用`Properties.load(InputStream)`加载文件,并遍历所有属性键,通过循环调用`getProperty(key)`获取每个键对应的值。
文章还提到了性能优化建议,包括使用`BufferedInputStream`来提高加载速度。同时,文章提醒读者在处理属性文件时,应确保文件路径正确,避免因路径错误导致的异常。此外,文章还强调了属性文件中键名的规范性,建议使用合法的名称以避免兼容性问题。
// 根据key读取value
public void readValue(String filePath, String key) {
// 根据key读取value
public void readValue(String filePath, String key) {
Properties props=new Properties();
InputStream in=new BufferedInputStream(new FileInputStream(filePath));
//Thread.currentThread().getContextClassLoader().getResourceAsStream(“eop.properties”);
props.load(in); // 从输入流中读取属性列表(键和元素对)
String value=props.getProperty(key);
}
// 读取properties的全部信息
public static void readProperties(String filePath) {
Properties props=new Properties();
InputStream in=new BufferedInputStream(new FileInputStream(filePath));
props.load(in);
Enumeration en=props.propertyNames();
while (en.hasMoreElements()) {
String key=(String) en.nextElement();
String value=props.getProperty(key);
}
}
© 版权声明
文章版权归作者所有,未经允许请勿转载。