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

JAVA读取配置文件路径

2009-05-25 13:26 316 查看
配置文件是应用系统中不可缺少的,可以增加程序
的灵活性.java.util.Properties是从jdk1.2就有的类,一直到现在都支持load
()方法,jdk1.4以后save(output,string)变成了store(output,string)

读取配置文件

,

xx.properties放在webroot/WEB-INF/classes/目录下

首先将配置文件转换成InputStream,有两种方式,原理一样,都是通过类加载器得到资源:

(1)InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream("xx.properties");

(2)

InputStream inputStream =

this.getClass()

.getClassLoader().getResourceAsStream(

"xx.properties"

);

调用对象的getClass()方法是获得对象当前的类类型,这部分数据存在方法区中,

而后在类类型上调用
getClassLoader()方法是得到当前类型的类加载器,我们知道在Java中所有的类都是通过加载器加载到虚拟机中的,而且类加载器之间存在父
子关系,就是子知道父,父不知道子,这样不同的子加载的类型之间是无法访问的(虽然它们都被放在方法区中),所以在这里通过当前类的加载器来加载资源也就
是保证是和类类型同一个加载器加载的。

最后调用了类加载器的getResourceAsStream()方法来加载资源。

然后加载配置文件,读取属性值

Properties prop = new Properties();

prop.load(input);

String value = prop.getProperty("PropertyName");

input.close();

修改配置文件:


Strign filename = "

xx.properties

";

InputStream inputStream = null;

FileOutputStream outputStream = null;

Properties p = new Properties();

try {

inputStream = this.getClass().getClassLoader().getResourceAsStream(filename);

//输入流要通过绝对路径得到

String path = pageContext.getServletContext().getRealPath("/")+

"/WEB-INF/classes/



//或者String path = this.getClass().getClassLoader().getResource("/").getPath()



outputStream = new FileOutputStream( path+ filename);

p.load(inputStream);

p.setProperty(propertyName, value).toString();

p.store(outputStream, "Description");

} catch (FileNotFoundException e2) {

e2.printStackTrace();

} catch (IOException e) {

e.printStackTrace();

}finally{

inputStream.close();

outputStream.close();

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: