java项目加载配置文件的工具类
package com.loadproperties;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class ConfigUtil {
private static InputStream input;
private volatile Properties configuration = new Properties();
//弄成单例的
private static ConfigUtil config;
public static ConfigUtil getInstance(String path){
if(config==null)
{
config=new ConfigUtil(path);
}
return config;
}
//构造函数内完成了加载配置文件
private ConfigUtil(String path)
{
input =this.getClass().getResourceAsStream(path);
this.configuration.clear();
try {
this.configuration.load(input);
} catch (IOException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}
public String getStringValue(String key) throws IOException
{
return this.configuration.getProperty(key);
}
public String getStringValue(String key, String defaultValue)
{
String value = this.configuration.getProperty(key);
if (value == null) {
return defaultValue;
} else {
return value;
}
}
public void setConfiguration(String key, String value)
{
this.configuration.setProperty(key, value);
}
public static void main(String[] args) throws IOException {
String path="/com/loadproperties/log4j.properties";
System.out.println(config.getInstance(path).getStringValue("log4j.rootLogger"));
}
}