JAVA读取配置文件路径

配置文件是应用系统中不可缺少的,可以增加程序 的灵活性.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();
        }

  

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值