Properties屬性文件在JAVA應用程序中是常常能夠看得見的,也是特別重要的一類文件,用來配置應用程序的一些信息,經過鍵值對的形式來保存。 java
1、經過spring的形式讀取 spring
一、spring配置文件: 框架
- <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
- <property name="locations">
- <list>
- <value>classpath:jdbc.properties</value>
- </list>
- </property>
- </bean>
二、自定義一個讀取Properties屬性文件的類,繼承自org.springframework.beans.factory.config.PropertyPlaceholderConfigurer ide
- public class CustomizedPropertyPlaceholderConfigurer extends
- PropertyPlaceholderConfigurer {
-
- private static Map<String, Object> ctxPropertiesMap;
-
- @Override
- protected void processProperties(
- ConfigurableListableBeanFactory beanFactoryToProcess,
- Properties props) throws BeansException {
- super.processProperties(beanFactoryToProcess, props);
- ctxPropertiesMap = new HashMap<String, Object>();
- for (Object key : props.keySet()) {
- String keyStr = key.toString();
- String value = props.getProperty(keyStr);
- ctxPropertiesMap.put(keyStr, value);
- } www.2cto.com
- }
-
- public static Object getContextProperty(String name) {
- return ctxPropertiesMap.get(name);
- }
-
- }
三、讀取屬性文件內容 this
String host = (String) CustomizedPropertyPlaceholderConfigurer.getContextProperty("mail.smtp.host"); spa
2、利用java.util.Properties讀取屬性文件 繼承
一、 資源
- InputStream path=this.getServletContext().getResourceAsStream("password.properties");
- //InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("password.properties");
-
- /*File filepath=new File(this.getServletContext().getRealPath("password.properties");
- InputStream path=new FileInputStream(filepath);*/
- Properties pros = new Properties();
- try {
- pros.load(path);
- } catch (IOException ex) {
- //System.out.println("file is not exist");
- errorMessage="資源文件不存在";
- }
- System.out.println("username:"+p.getProperty("username")+",password:"+p.getProperty("password"));
二、 get
- ClassPathResource cr = new ClassPathResource("password.properties");//會從新加載spring框架
- Properties pros = new Properties();
- try {
- pros.load(cr.getInputStream());
- } catch (IOException ex) {
- //System.out.println("file is not exist");
- errorMessage="資源文件不存在";
- }