如何获取配置文件的内容

读取properties文件的工具类:

package com.jtv.util;

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

import org.apache.log4j.Logger;

public final class EnvPathList extends Properties {
private static Logger logger = Logger.getLogger(EnvPathList.class);
private static EnvPathList instance;

public static EnvPathList getInstance() {
if (instance != null) {
return instance;
}
else {
makeInstance();
return instance;
}
}

// 同步方法,保证在同一时间,只能被一个人调用
private static synchronized void makeInstance() {
if (instance == null) {
instance = new EnvPathList();
}
}

private EnvPathList() {
try {
InputStreamReader is = new InputStreamReader(getClass().getResourceAsStream(
"/pathList.properties"), "UTF-8");
load(is);
} catch (UnsupportedEncodingException ee) {
logger.error(com.jtv.util.DateUtils.getCurrTime() + "错误:读取属性文件失败,当前编码格式不支持.", ee);
} catch (Exception e) {
logger.error(com.jtv.util.DateUtils.getCurrTime()
+ "错误:没有读取属性文件,请确认pathList.properties文件是否存在.", e);
}
}

}


调用示例:

public class test{
   public static void main(String []args){
       String val = EnvPathList.getInstance().getProperty("userName").trim();
       String password=EnvPathList.getInstance().getProperty("password").trim();
       System.out.println("userName="+userName+"\npassword="+password);   
    }
}

注: 配置文件放于文件根目录下,因为/pathList.properties 表示从根目录下进行查找文件。 同时配置文件中预先设置了 userName和password的值。

猜你喜欢

转载自greatexpectations.iteye.com/blog/2355831