java读取Properties属性文件的方法

Properties属性文件在JAVA应用程序中是常常能够看得见的,也是特别重要的一类文件,用来配置应用程序的一些信息,经过键值对的形式来保存。 java

 

1、经过spring的形式读取 spring

一、spring配置文件: 框架

Xml代码
  1. <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">     
  2.        <property name="locations">     
  3.             <list>     
  4.                <value>classpath:jdbc.properties</value>     
  5.             </list>     
  6.        </property>     
  7. </bean>     

 二、自定义一个读取Properties属性文件的类,继承自org.springframework.beans.factory.config.PropertyPlaceholderConfigurer ide

Java代码
  1. public class CustomizedPropertyPlaceholderConfigurer extends   
  2.         PropertyPlaceholderConfigurer {   
  3.    
  4.     private static Map<String, Object> ctxPropertiesMap;   
  5.    
  6.     @Override   
  7.     protected void processProperties(   
  8.             ConfigurableListableBeanFactory beanFactoryToProcess,   
  9.             Properties props) throws BeansException {   
  10.         super.processProperties(beanFactoryToProcess, props);   
  11.         ctxPropertiesMap = new HashMap<String, Object>();   
  12.         for (Object key : props.keySet()) {   
  13.             String keyStr = key.toString();   
  14.             String value = props.getProperty(keyStr);   
  15.             ctxPropertiesMap.put(keyStr, value);   
  16.         }   www.2cto.com  
  17.     }   
  18.    
  19.     public static Object getContextProperty(String name) {   
  20.         return ctxPropertiesMap.get(name);   
  21.     }   
  22.    
  23. }   

 三、读取属性文件内容 this

String host =  (String) CustomizedPropertyPlaceholderConfigurer.getContextProperty("mail.smtp.host"); spa

2、利用java.util.Properties读取属性文件 继承

一、 资源

Java代码
  1. InputStream path=this.getServletContext().getResourceAsStream("password.properties");  
  2.        //InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("password.properties");  
  3.   
  4.    /*File filepath=new File(this.getServletContext().getRealPath("password.properties"); 
  5.        InputStream path=new FileInputStream(filepath);*/  
  6.        Properties pros = new Properties();  
  7.        try {  
  8.            pros.load(path);  
  9.        } catch (IOException ex) {  
  10.            //System.out.println("file is not exist");  
  11.            errorMessage="资源文件不存在";  
  12.        }  
  13.        System.out.println("username:"+p.getProperty("username")+",password:"+p.getProperty("password"));  

 二、 get

Java代码
  1. ClassPathResource cr = new ClassPathResource("password.properties");//会从新加载spring框架  
  2.        Properties pros = new Properties();  
  3.        try {  
  4.            pros.load(cr.getInputStream());  
  5.        } catch (IOException ex) {  
  6.            //System.out.println("file is not exist");  
  7.            errorMessage="资源文件不存在";  
  8.        }  
相关文章
相关标签/搜索