ublic class PropUtil
{
public static Properties getPropUtil () {
Properties config = new Properties();
InputStream is = null;
try {
//这种方法读取后,文件会放到内存中,以后都从内存中读取,不能实时读取。
is = PropUtil .class.getClassLoader().getResourceAsStream("prop.properties");
config.load(is);
} catch (IOException e) {
} finally {//关闭资源
if (is != null) {
try {
is.close();
} catch (IOException e) {
}
}
}
log.debug("return prop config");
return config;
}
}
代码2:
Java代码
public class PropUtil {
private static ResourceBundle resources;
public static String getParam(String confFileName,String param) {
resources = ResourceBundle.getBundle(confFileName);
return resources.getString(param);
}
}
代码3:
Java代码
public static String getParameter(String key){
Properties params = new Properties();
FileInputStream in = null;
String value =null;
try
{
in = new FileInputStream("prop.properties");
params.load(in);
value = params.getProperty(key);
}
catch (java.io.IOException e)
{
e.printStackTrace();
}finally {
if(in!=null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return value;
}
public static void main(String[] args) throws IOException {
//java环境测试
InputStream is = ClassLoader.getSystemResourceAsStream("mongDB.properties");
Properties p = new Properties();
p.load(is);
System.out.println( p.get("url"));
}
加载配置文件的时候spring用
ClassLoader classLoader = Thread.currentThread().getContextClassLoader();
InputStream is = classLoader.getResourceAsStream("") ;
网上摘录:
http://www.iteye.com/topic/1126812
public class ConstantConstants {
private static ConstantConstants instance;
private Properties constantsProp;
/**
* 单例
*/
public static ConstantConstants getInstance(){
if(instance==null){
instance = new ConstantConstants();
return instance;
}else{
return instance;
}
}
/**
* 属性文件只读一次
*/
public String getProperty(String key) {
try {
if(constantsProp!=null){
return (String) constantsProp.get(key );
}else{
constantsProp = new Properties();
String path = this.getClass().getResource("").getPath()+"constants.properties";
InputStream is = new FileInputStream(new File(path));
constantsProp.load(is);
String rs = (String) constantsProp.get(key);
if (is != null) {
is.close();
}
return rs;
}
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 修改某个key的 值
*/
public void editPro(String key ,String value){
if(key==null || "".equals(key)
|| value==null || "".equals(value)){
log.info("fail to write law constants ");
return ;
}
try {
String values = ConstantConstants.getInstance().getProperty( key);
String[] vs = values.split(",");
if(vs==null || vs.length==0 ){
return ;
}
List list = Arrays.asList(vs );
if(!list.contains(value )){
constantsProp.setProperty(key, values+","+value);
String path = this.getClass().getResource("").getPath()+"constant.properties";
OutputStream os = new FileOutputStream(new File(path));
constantsProp.store( os, " ");
os.flush();
os.close();
}
//以便下次数据的重新载入
constantsProp = null;
} catch (IOException e) {
e.printStackTrace();
}
}
}