Java读取Properties文件

来源:互联网 发布:海洋cms怎么更换模板 编辑:程序博客网 时间:2024/05/14 04:24

最常用读取properties文件的方法

InputStream in = getClass().getResourceAsStream("资源Name");

这种方式要求properties文件和当前类在同一文件夹下面。如果在不同的包中,必须使用:
InputStream ins = this.getClass().getResourceAsStream("/cn/zhao/properties/testPropertiesPath2.properties");

这里面有个问题,就是getClass()调用的时候有时候会省略了this!我们都知道,this是不能在static(静态)方法或者static块中使用的,原因是static类型的方法或者代码块是属于类本身的,不属于某个对象,而this本身就代表当前对象,而静态方法或者块调用的时候是不用初始化对象的。


解决方法:

Properties prop = new Properties();InputStream in = Object.class.getResourceAsStream("/test.properties"); 


完整代码如下:
Properties prop = new Properties();InputStream in = Object.class.getResourceAsStream("/test.properties");try {prop.load(in);param1 = prop.getProperty("initYears1").trim();param2 = prop.getProperty("initYears2").trim();} catch (IOException e) {e.printStackTrace();}


可以通过
prop.entrySet().iterator()
获取 iterator迭代器类型结果,可以像Map对象一样遍历它。


0 0
原创粉丝点击