博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
java 如何读取src根目录下的属性文件
阅读量:6903 次
发布时间:2019-06-27

本文共 1491 字,大约阅读时间需要 4 分钟。

在项目中,如何获取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

转载地址:http://zqvdl.baihongyu.com/

你可能感兴趣的文章
Leetcode#75Sort Colorsetcode
查看>>
3月30日作业
查看>>
公司电话突然不能打外线故障处理过程
查看>>
Windows Server 2008流媒体服务器---创建播放列表
查看>>
centos添加批量添加ip提示无效参数
查看>>
PHP mkdir函数
查看>>
Linux基础命令---检查密码文件pwck
查看>>
python这+=和=的拓展知识
查看>>
oracle集群件
查看>>
linux shell 中"2>&1"含义
查看>>
oracle 11g RAC grid安装前准备
查看>>
01背包 暴力搜索
查看>>
RIP区域和OSPF区域通信
查看>>
MySQL
查看>>
网络安全系列之四十 在Linux中设置SET位权限
查看>>
SCCM OSD部署排错
查看>>
十道非常好的shell脚本试题
查看>>
app项目案例一手机浏览器
查看>>
java 中 isEmpty和isBlank区别
查看>>
申请SSL证书怎样验证域名所有权
查看>>