Java中读取资源文件的工具类

时间:2022-08-31 17:38:33
package com.justsy;

import java.io.InputStream;
import java.util.Properties;

public class PropertiesManager {

private String resName = "appstore.properties";

private Properties prop = new Properties();

public PropertiesManager configuration() {

try {
InputStream is = PropertiesManager.class.getClassLoader()
.getResourceAsStream(resName);
prop.load(is);
if (is != null)
is.close();
} catch (Exception e) {
System.out.println(e + "file " + resName + " not found");
}
return this;
}

public String getPara(String url) {
return prop.getProperty(url);
}

public static void main(String[] args) {
PropertiesManager pm = new PropertiesManager().configuration() ;

System.out.println(pm.getPara("url"));
}

}
 
 

使用单例进行优化后的工具类

package com.justsy.eas.util;

import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.apache.log4j.Logger;
/**
* 读取配置文件
*/
public class PropertiesReader {
private Logger logger = Logger.getLogger(Properties.class) ;
private Properties properties ;
private static PropertiesReader propertiesReader = new PropertiesReader() ;

private String resName = "eas.properties" ;

// 单例私有化构造方法
private PropertiesReader(){
InputStream is = PropertiesReader.class.getClassLoader()
.getResourceAsStream(resName);
properties = new Properties() ;
try {
properties.load(is);
logger.info("加载配置信息!!") ;
} catch (IOException e) {
logger.warn("加载配置文件出错!") ;
//e.printStackTrace();
}
}

// 得到PropertiesReader的实例
public static PropertiesReader getInstance(){
if(propertiesReader==null){
return new PropertiesReader() ;
}
return propertiesReader ;
}

// 返回所有属性
public Properties getProperties(){
return this.properties ;
}

public static void main(String[] args) {
Properties properties = PropertiesReader.getInstance().getProperties() ;
System.out.println(properties.getProperty("dbaddr"));
}

}