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();

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

  • 相关阅读:
    数数小木块
    猴子吃桃问题
    整除个数
    大小写互换
    车牌号
    比较字母大小
    队花的烦恼一
    字母小游戏
    字符串逆序输出
    茵茵的第一课
  • 原文地址:https://www.cnblogs.com/bffc/p/3711736.html
Copyright © 2011-2022 走看看