properties文件的读取

一、问题阐述

 

本文给出了读取properties文件的简单实例。重点在于解释如果定位properties文件在项目中的相对目录。

 

二、代码

 

1. properties文件named ipConfig:

 

   ip=192.168.0.1  

   port=8080

 

2. 读取文件的代码:

 

   InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("ipConfig.properties");  
   Properties p = new Properties();  
   try {  
         p.load(inputStream);  
      } catch (IOException e1) {  
       e1.printStackTrace();  
      }  
   System.out.println("ip:"+p.getProperty("ip")+",port:"+p.getProperty("port"));

 

其中this.getClass().getClassLoader().getResourceAsStream("ipConfig.properties")中的this是执行这段代码的类,ipConfig.properties与this这个类必在同一级目录下,即在一个folder里。因此,如果想找到ipConfig.properties,你就可以在以上方法中直接new出与ipConfig.properties在同一级目录下的任一Class,例如Class c = new Class(); 然后就可以通过 c.getClass().getClassLoader().getResourceAsStream("ipConfig.properties")来得到ipConfig.properties的InputStream。

 

 

 

你可能感兴趣的:(c,properties,Class)