您的位置:首页 > 编程语言 > Java开发

java 读取项目properties文件

2017-07-25 15:52 399 查看
  项目经常使用到.properties配置文件,读取这些文件的方法有很多,下面介绍一种最基础的方法,使用class.getClassLoader().getResourceAsStream 加载到静态资源类中.

  


  1. 首先需要解释一下class.getClassLoader().getResourceAsStream 和.class.getResourceAsStream 加载系统文件规则

  (A) class.getClassLoader().getResourceAsStream() 加载项目中的文件.该方法加载文件起始根目录为classes.如 .class.getClassLoader().getResourceAsStream(“config/system.development.properties”);读取的是上面截图中的文件system.development.properties(因为使用了maven, 所以system.development.properties也存在于classes/config 目录下).注意使用这种方法,参数不能以/开始.

  (B) *.class.getResourceAsStream() 参数有两种形式

   (1) 以/ 开始,表示绝对路径,这个路径以classes作为根目录.那么*.class.getResourceAsStream(“/config/system.development.properties”)文件读取的就是classes/config/1.properties 文件.这和(A) 读取的是同一个文件.

   (2) 相对路径. *.class.getResourceAsStream(“1.properties”)读取的是该class文件同级目录下的1.properties文件.

 个人习惯,更倾向于*class.getClassLoader().getResourceAsStream(“”)方式.

了解了如上加载文件规则后,如下加载properties文件.

public class PropertyUtil {
private static Properties props;
static {
loadProps();
}

synchronized static private void loadProps() {
props = new Properties();
InputStream in = null;
try {
// (A)*.class.getClassLoader().getResourceAsStream 读取文件文件根目录为classes, 并且参数不能以/开头
in = PropertyUtil.class.getClassLoader().getResourceAsStream("config/system.development.properties");

// (B) *.class.getResourceAsStream 读取classes/config/system.development.properties 注意参数以/开始
// in = PropertyUtil.class.getResourceAsStream("/config/system.development.properties");

// (C) *.class.getResourceAsStream 读取和此class文件同级的1.properties文件(注意没有以/开始)
// in = PropertyUtil.class.getResourceAsStream("1.properties");

props.load(in);
} catch (FileNotFoundException e) {
} catch (IOException e) {
} finally {
try {
if (null != in) {
in.close();
}
} catch (IOException e) {
}
}
}

public static String getProperty(String key) {
if (null == props) {
loadProps();
}
return props.getProperty(key);
}

public static String getProperty(String key, String defaultValue) {
if (null == props) {
loadProps();
}
return props.getProperty(key, defaultValue);
}

public static void main(String[] args) {
Enumeration e = props.propertyNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
System.out.println(key + ":\t" + props.get(key));
}
}
}


至此完成了properties文件加载. 系统java 文件可以是用静态方法来获取相应的配置了.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息