讀properties文件和寫properties文件

讀文件很簡單:

Java代碼  收藏代碼
  1. public static String getProperty(String key) {  
  2.         String value = "";  
  3. //第一步是取得一個Properties對象  
  4.         Properties props = new Properties();  
  5. //第二步是取得配置文件的輸入流  
  6.         InputStream is = PropUtil.class.getClassLoader().getResourceAsStream("config.properties");//在非WEB環境下用這種方式比較方便  
  7.         try {  
  8.             InputStream input = new FileInputStream("config.properties");//在WEB環境下用這種方式比較方便,不過當配置文件是放在非Classpath目錄下的時候也需要用這種方式  
  9. //第三步講配置文件的輸入流load到Properties對象中,這樣在後面就可以直接取來用了  
  10.             props.load(input);  
  11.             value = props.getProperty(key);  
  12.             is.close();  
  13.         } catch (IOException e) {  
  14.             // TODO Auto-generated catch block  
  15.             e.printStackTrace();  
  16.         }  
  17.         return value;  
  18.     }  

 

往配置文件裏面寫內容:

Java代碼  收藏代碼
  1. public static void setProperty(Map<String,String> data) {  
  2. //第一步也是取得一個Properties對象  
  3.         Properties props = new Properties();  
  4. //第二步也是取得該配置文件的輸入流  
  5. //      InputStream is = PropUtil.class.getClassLoader().getResourceAsStream("config.properties");  
  6.         try {  
  7.             InputStream input = new FileInputStream("config.properties");  
  8. //第三步是把配置文件的輸入流load到Properties對象中,  
  9.             props.load(input);  
  10. //接下來就可以隨便往配置文件裏面添加內容了  
  11. //          props.setProperty(key, value);  
  12.             if (data != null) {  
  13.                 Iterator<Entry<String,String>> iter = data.entrySet().iterator();  
  14.                 while (iter.hasNext()) {  
  15.                     Entry<String,String> entry = iter.next();  
  16.                     props.setProperty(entry.getKey().toString(), entry.getValue().toString());  
  17.                 }  
  18.             }  
  19. //在保存配置文件之前還需要取得該配置文件的輸出流,<span style="color: #ff0000; font-size: medium;">切記,</span>如果該項目是需要導出的且是一個非WEB項目,則該配置文件應當放在根目錄下,否則會提示找不到配置文件  
  20.             OutputStream out = new FileOutputStream("config.properties");  
  21. //最後就是利用Properties對象保存配置文件的輸出流到文件中;  
  22.             props.store(out, null);  
  23.             input.close();  
  24.             out.close();  
  25.         } catch (IOException e) {  
  26.             // TODO Auto-generated catch block  
  27.             e.printStackTrace();  
  28.         }  
  29.     } 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章