java 如何读取src根目录下的属性文件

Java项目中,如何获取src根目录下的属性文件/资源文件呢?

有如下三种方式:

方式一:

Java代码   收藏代码
  1. InputStream in = Test.class   
  2.         .getResourceAsStream("/env.properties");  
  3. URL url = Test.class.getResource("<span style="color: #000000;">/</span>env.properties")  ;  

 说明:env.properties文件在src的根目录下,文件名前有斜杠

 

方式二:

Java代码   收藏代码
  1. InputStream in = Test.class.getClassLoader()    
  2.       .getResourceAsStream("env.properties");  
  3. URL url = Test.class.getClassLoader().getResource("env.properties")  ;  

 

 

方式三:

Java代码   收藏代码
  1. InputStream in = Thread.currentThread().getContextClassLoader()  
  2.                 .getResourceAsStream("ExcelModeMappingl.xml");  

 示例:

Java代码   收藏代码
  1. /*** 
  2.      *  
  3.      * @param filePath 
  4.      * @return 
  5.      * @throws IOException 
  6.      */  
  7.     public static Properties getProperties(String filePath) throws IOException {  
  8.         InputStream in = Thread.currentThread().getContextClassLoader()  
  9.                 .getResourceAsStream(filePath);  
  10.         Properties prop = new Properties();  
  11.         try {  
  12.             prop.load(in);  
  13.         } catch (IOException e) {  
  14.             e.printStackTrace();  
  15.         } finally {  
  16.             if (in != null) {  
  17.                 in.close();  
  18.             }  
  19.         }  
  20.         return prop;  
  21.     }  

 测试1:

Java代码   收藏代码
  1. @Test  
  2.     public void test_GenericReadPropsUtil() throws IOException{  
  3.         Properties pro=GenericReadPropsUtil.getProperties("test_switch.properties");  
  4.         System.out.println(pro.get("name"));  
  5.     }  

 说明:

test_switch.properties 的位置与 com 同级目录,即 test_switch.properties在src根目录下。

 

 

测试2

Java代码   收藏代码
  1. @Test  
  2.     public void test_GenericReadPropsUtil() throws IOException{  
  3.         Properties pro=GenericReadPropsUtil.getProperties("com/wh/test_switch.properties");  
  4.         System.out.println(pro.get("endpoint.isSelfCheck"));  
  5.     }  

 说明:

test_switch.properties的位置:com/wh/test_switch.properties

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值