java采用 java.util.Properties类读取配置文件
java.util.Properties是对properties这类配置文件的映射。支持key-value类型和xml类型两种。
package com.guo.core.config;
import java.util.HashMap;
import java.util.Map;
/**
* <pre>
* 智能配置文件读取类管理池,通过该管理池获得的配置文件的属性值
* [1]:比如配置文件application.properties在目录src下使用如下方式。
* <p>
* ConfigFile cfg = ConfigFileFactory.getInstance().getConfigFile("application");
* String value = cfg.getValue("value");
* </p>
* </pre>
*/
public class ConfigfileFactory {
private static ConfigfileFactory instance = null;
private String extendsname = ".properties";
private Map hashmap = new HashMap();
//构造函数私有化,禁止外部创建
private ConfigfileFactory(){}
//采用单例模式,创建单一工厂,synchronized保证线程安全性
public synchronized static ConfigfileFactory getInstance(){
if(null == instance){
instance = new ConfigfileFactory();
}
return instance;
}
public ConfigFile getConfigFile(String fileneme) throws Exception{
ConfigFile configfile = (ConfigFile)hashmap.get(fileneme);
if(null == configfile){
configfile = new ConfigFile(fileneme+extendsname);
hashmap.put(fileneme, configfile);
}
return configfile;
}
public int getConfigSize(){
return hashmap.size();
}
}
package com.guo.core.config;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.util.Properties;
/**
* <pre>
* 读取配置文件
* 该配置文件读取类在程序运行过程如果配置文件更改了的话
* 会自动重新装载配置文件,不用停应用服务
* </pre>
*
* @author guoqingping
* @since 2015/11/10
* @version 1.0
*/
public class ConfigFile {
private Properties properties;
private String config_file_name; //文件名
public String getConfig_file_name() {
return config_file_name;
}
public void setConfig_file_name(String config_file_name) {
this.config_file_name = config_file_name;
}
public ConfigFile(){}
public ConfigFile(String config_file_name) throws Exception{
this.config_file_name = config_file_name;
properties = loadConfigProperties(config_file_name);
}
public Properties loadConfigProperties(String config_file_name) throws Exception{
Properties properties = new Properties();
InputStream in = new FileInputStream(getFile(config_file_name));
properties.load(in);
return properties;
}
public File getFile(String filename) throws Exception{
if(null == filename){
throw new Exception("文件名为空!");
}
File file = null;
//在项目的classes路径下查找文件,/表示calsses根目录
URL url = ConfigFile.class.getResource("/"+filename);
if(null == url){
throw new Exception("The File"+filename+"is Not Found!");
}
file = new File(url.getPath());
if(file.exists()&&file.isFile()&&file.canRead()){
return file;
}
return null;
}
public String getvalue(String key) throws Exception{
//properties非final,再次加载,以防properties为null
properties = loadConfigProperties(config_file_name);
String value = properties.getProperty(key);
return value;
}
public String getvalue(String key,String defaultvalue) throws Exception{
//properties非final,再次加载,以防properties为null
properties = loadConfigProperties(config_file_name);
String value = properties.getProperty(key);
if(null == value){
value = defaultvalue;
}
return value;
}
}