尝试一下封装一个读取Properties工具类,自己大概看了看DBUtils和Druid源码,学习一下封装思想,希望有大佬指点。
public class PropertiesUtil {
private Properties properties = null;
private String fileName = null;
private Logger log = Logger.getLogger(PropertiesUtil.class);
public PropertiesUtil(){
}
public PropertiesUtil(String fileName){
this.fileName = fileName;
}
private void creatProperties(){
if(this.fileName == null){
log.error("PropertiesUtil|error|配置文件未设置");
throw new RuntimeException("配置文件未设置");
}
log.info("PropertiesUtil|info|fileName:" + this.fileName);
if(!this.fileName.endsWith(".properties")){
log.error("PropertiesUtil|error|文件格式错误");
throw new RuntimeException("文件格式错误");
}
this.properties = new Properties();
}
public String getValue(String key){
return this.getValue(null,key);
}
/*
通过key值读取配置文件的单一值
*/
public String getValue(String fileName,String key) throws RuntimeException{
if(fileName != null){
this.fileName = fileName;
}
if(this.properties == null){
creatProperties();
fileReadLoad();
}
Object val = this.properties.get(key);
if(val == null){
log.error("PropertiesUtil|error|没有找到对应的值!");
throw new RuntimeException("没有找到对应的值!");
}
return val.toString();
}
public void setValue(Map<String, String> map){
this.setValue(null,map);
}
public void setValue(String fileName,Map<String, String> map){
if (fileName != null){
this.fileName = fileName;
}
creatProperties();
Set<String> keySet = map.keySet();
Iterator<String> iterator = keySet.iterator();
while (iterator.hasNext()){
String key = iterator.next();
setProperties(key,map.get(key));
}
fileOutLoad();
}
public void setValue(String key,String val){
this.setValue(this.fileName,key,val);
}
/*
向配置文件里保存数据
*/
public void setValue(String fileName,String key,String val){
if (fileName != null){
this.fileName = fileName;
}
creatProperties();
setProperties(key,val);
fileOutLoad();
}
private void setProperties(String key,String val){
this.properties.setProperty(key,val);
}
/*
加载配置文件
*/
private void fileReadLoad(){
InputStream in = PropertiesUtil.class.getClassLoader().getResourceAsStream(this.fileName);
if(in == null){
log.error("PropertiesUtil|error|配置文件设置错误");
throw new RuntimeException("配置文件设置错误");
}
try {
this.properties.load(in);
} catch (IOException e) {
e.printStackTrace();
}
}
/*
保存配置文件
*/
private void fileOutLoad(){
File file = new File("bin" + File.separator + this.fileName);
FileOutputStream fileOutputStream = null;
try {
fileOutputStream = new FileOutputStream(file);
this.properties.store(fileOutputStream, String.valueOf(System.nanoTime() + "--" + Math.random()));
} catch (Exception e) {
log.error("PropertiesUtil|error|" + e.getMessage());
e.printStackTrace();
}finally {
try {
if(fileOutputStream != null){
fileOutputStream.close();
}
} catch (IOException e) {
log.error("PropertiesUtil|error|" + e.getMessage());
e.printStackTrace();
}
if(this.properties != null){
this.properties.clear();
}
}
}
}