zoukankan      html  css  js  c++  java
  • Java加载配置文件的方式

    1.通过文件流来加载

    1 InputStream in=  new FileInputStream("sample.properties");     
    2 Properties properties = new Properties();
    3 properties .load(in);

    这种方式采用相对路径的方式加载,对于不同的系统、不同的运行环境不一定全都能正确加载

    2.采用ClassLoader的getResourceAsStream方式进行加载

    1 InputStream in = PropertiesTest.class.getClassLoader().getResourceAsStream("sample.properties");  
    2 Properties properties = new Properties();
    3 properties .load(in);

    对于这种方式,getClassLoader()的默认位置是classes文件夹,但是如果类加载是委托机制,将有可能加载不成功

    3.采用Class的getResourceAsStream方式进行加载

    1 InputStream in = PropertiesTest.class.getResourceAsStream("sample.properties");  
    2 Properties properties = new Properties();
    3 properties .load(in);

    对于这种方式,默认加载位置是class文件对应的位置

    此外通过

    1.PropertiesTest.class.getResource("sample.properties").getPath();

    2.PropertiesTest.class.getClassLoader().getResource("sample.properties").getPath();

    两种方式都可以获取文件的相对路径

  • 相关阅读:
    《人月神话》阅读笔记02
    《人月神话》阅读笔记01
    第十四周学习进度条
    我们做的作品 请大家多多支持我们
    Beta阶段项目总结
    Alpha阶段项目总结
    Alpha版总结会议
    站立会议10(第二次冲刺)
    站立会议09(第二次冲刺)
    站立会议08(第二次冲刺)
  • 原文地址:https://www.cnblogs.com/bffc/p/3711736.html
Copyright © 2011-2022 走看看