您的位置:首页 > 编程语言 > Java开发

Java读取properties配置文件

2011-08-05 13:05 561 查看
Java读取properties配置文件

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class Property {

private static Map<String, String> propertyMap = new HashMap<String, String>();

private String fileName;

public Property(String fileName) {
this.fileName = fileName;
}

public String getProperty(String key) throws FileNotFoundException, IOException {
String value = Property.propertyMap.get(key);
Properties property = new Properties();
FileInputStream inputFile = null;

if (value == null) {
// 实例化inputFile,如config.properties文件的位置
inputFile = new FileInputStream(this.fileName);
// 装载配置文件
property.load(inputFile);

value = property.getProperty(key);
Property.propertyMap.put(key, value);
}
return value;
}

public Map<String,String> getProperty(List<String> propertyList) throws FileNotFoundException, IOException {
// 定义Map用于存放结果
Map<String,String> propertyMap = new HashMap<String,String>();
// 定义Properties property = new Properties();
Properties property = new Properties();
// 定义FileInputStream inputFile = null;
FileInputStream inputFile = null;

try {
// 实例化inputFile
inputFile = new FileInputStream(this.fileName);
// 装载配置文件
property.load(inputFile);
for (String name : propertyList) {
// 从配置文件中获取属性存入map中
String data = property.getProperty(name);
propertyMap.put(name, data);
}

} finally {
// 关闭输入流
if (inputFile != null) {
inputFile.close();
}
}

return propertyMap;
}
}


 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息