1. 程式人生 > >java 4種方式讀取配置檔案 + 修改配置檔案

java 4種方式讀取配置檔案 + 修改配置檔案

方式一:採用ServletContext讀取,讀取配置檔案的realpath,然後通過檔案流讀取出來。

因為是用ServletContext讀取檔案路徑,所以配置檔案可以放入在web-infoclasses目錄中,也可以在應用層級及web-info的目錄中。檔案存放位置具體在eclipse工程中的表現是:可以放在src下面,也可放在web-infowebroot下面等。因為是讀取出路徑後,用檔案流進行讀取的,所以可以讀取任意的配置檔案包括xmlproperties。缺點:不能在servlet外面應用讀取配置資訊。

具體舉例如下:

//ServletContext.getRealPath(name)

讀取路徑

privatevoid test1(HttpServletRequest request, HttpServletResponseresponse)

throwsServletException,IOException {

//response.setContentType("text/html;charset=utf-8");

String path = "/WEB-INF/jdbc_connection.properties"//讀取WEB-INF中的配置檔案

String realPath = getServletContext().getRealPath(path);//getServletContext()

相當於http://localhost/demo05

//所以後面的path只需要以應用demo/開頭具體的部署目錄路徑即可,如上面的/web-in…

System.out.println(realPath);

InputStreamReader reader =new InputStreamReader(newFileInputStream(realPath),"utf-8");

Properties props = new Properties();

props.load(reader); //load個人建議還是用Reader來讀,因為reader體系中有個InputStreamReader可以指定編碼

String jdbcConValue = props.getProperty("jdbc_con"

);

System.out.println(jdbcConValue);

System.out.println("載入src包下的資源------------------------");

path = "/WEB-INF/classes/com/test/servlet/jdbc_connection.properties"//讀取WEB-INF中的配置檔案

    realPath=getServletContext().getRealPath(path);

System.out.println(realPath);

reader = new InputStreamReader(new FileInputStream(realPath),"utf-8");

props.load(reader); //load個人建議還是用Reader來讀,因為reader體系中有個InputStreamReader可以指定編碼

jdbcConValue = props.getProperty("jdbc_con");

System.out.println("second::"+jdbcConValue);

}

方式二:採用ResourceBundle類讀取配置資訊,

優點是:可以以完全限定類名的方式載入資源後,直接的讀取出來,且可以在非Web應用中讀取資原始檔。

缺點:只能載入類classes下面的資原始檔且只能讀取.properties檔案。

  1. /** 
  2.  * 獲取指定配置檔案中所以的資料 
  3.  * @param propertyName 
  4.  *        呼叫方式: 
  5.  *            1.配置檔案放在resource源包下,不用加字尾 
  6.  *              PropertiesUtil.getAllMessage("message"); 
  7.  *            2.放在包裡面的 
  8.  *              PropertiesUtil.getAllMessage("com.test.message"); 
  9.  * @return 
  10.  */
  11. publicstatic List<String> getAllMessage(String propertyName) {  
  12.     // 獲得資源包
  13.     ResourceBundle rb = ResourceBundle.getBundle(propertyName.trim());  
  14.     // 通過資源包拿到所有的key
  15.     Enumeration<String> allKey = rb.getKeys();  
  16.     // 遍歷key 得到 value
  17.     List<String> valList = new ArrayList<String>();  
  18.     while (allKey.hasMoreElements()) {  
  19.         String key = allKey.nextElement();  
  20.         String value = (String) rb.getString(key);  
  21.         valList.add(value);  
  22.     }  
  23.     return valList;  
  24. }  

方式三:採用ClassLoader方式進行讀取配置資訊

優點是:可以在非Web應用中讀取配置資源資訊,可以讀取任意的資原始檔資訊  缺點:只能載入類classes下面的資原始檔。
  1. /**獲取的是class的根路徑下的檔案 
  2.      * 優點是:可以在非Web應用中讀取配置資源資訊,可以讀取任意的資原始檔資訊 
  3.      * 缺點:只能載入類classes下面的資原始檔。 
  4.      * 如果要加上路徑的話:com/test/servlet/jdbc_connection.properties 
  5.      */
  6.     privatestaticvoid use_classLoador(){  
  7.         //檔案在class的根路徑
  8.         InputStream is=TestJava.class.getClassLoader().getResourceAsStream("message.properties");  
  9.         //獲取檔案的位置
  10.         String filePath=TestJava.class.getClassLoader().getResource("message.properties").getFile();  
  11.         System.out.println(filePath);  
  12.         //獲取的是TestJava類所在的相對路徑下 ,com/test/servlet/jdbc_connection.properties"
  13. //      InputStream is2=TestJava.class.getResourceAsStream("message.propertie");
  14.         BufferedReader br= new BufferedReader(new InputStreamReader(is));  
  15.         Properties props = new Properties();  
  16.         try {  
  17.             props.load(br);  
  18.             for (Object s : props.keySet())   
  19.                 System.out.println(s);  
  20.         } catch (IOException e) {   e.printStackTrace();}  
  21.     }  

方法4 getResouceAsStream

XmlParserHandler.class.getResourceAsStream 與classloader不同
使用的是當前類的相對路徑
  1. BufferedReader br=new BufferedReader(    
  2.         new InputStreamReader(XmlParserHandler.class.    
  3.                 getResourceAsStream("./rain.xml"), "GB2312"));// ./代表當前目錄不寫也可以  
  4. InputSource is=new InputSource(br);//資料來源  

方法5 PropertiesLoaderUtils工具類

  1. /** 
  2.  * Spring 提供的 PropertiesLoaderUtils 允許您直接通過基於類路徑的檔案地址載入屬性資源 
  3.  * 最大的好處就是:實時載入配置檔案,修改後立即生效,不必重啟 
  4.  */
  5. privatestaticvoid springUtil(){  
  6.     Properties props = new Properties();  
  7.     while(true){  
  8.         try {  
  9.             props=PropertiesLoaderUtils.loadAllProperties("message.properties");  
  10.             for(Object key:props.keySet()){  
  11.                 System.out.print(key+":");  
  12.                 System.out.println(props.get(key));  
  13.             }  
  14.         } catch (IOException e) {  
  15.             System.out.println(e.getMessage());  
  16.         }  
  17.         try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}  
  18.     }  
  19. }  

修改Properties

  1. /** 
  2.      * 傳遞鍵值對的Map,更新properties檔案 
  3.      *  
  4.      * @param fileName 
  5.      *            檔名(放在resource源包目錄下),需要字尾 
  6.      * @param keyValueMap 
  7.      *            鍵值對Map 
  8.      */
  9.     publicstaticvoid updateProperties(String fileName,Map<String, String> keyValueMap) {  
  10.         //getResource方法使用了utf-8對路徑資訊進行了編碼,當路徑中存在中文和空格時,他會對這些字元進行轉換,這樣,
  11.         //得到的往往不是我們想要的真實路徑,在此,呼叫了URLDecoder的decode方法進行解碼,以便得到原始的中文及空格路徑。
  12.         String filePath = PropertiesUtil.class.getClassLoader().getResource(fileName).getFile();  
  13.         Properties props = null;  
  14.         BufferedWriter bw = null;  
  15.         try {  
  16.             filePath = URLDecoder.decode(filePath,"utf-8");      
  17.             log.debug("updateProperties propertiesPath:" + filePath);  
  18.             props = PropertiesLoaderUtils.loadProperties(new ClassPathResource(fileName));  
  19.             log.debug("updateProperties old:"+props);  
  20.             // 寫入屬性檔案
  21.             bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath)));  
  22.             props.clear();// 清空舊的檔案
  23.             for (String key : keyValueMap.keySet())  
  24.                 props.setProperty(key, keyValueMap.get(key));  
  25.             log.debug("updateProperties new:"+props);  
  26.             props.store(bw, "");  
  27.         } catch (IOException e) {  
  28.             log.error(e.getMessage());  
  29.         } finally {  
  30.             try {  
  31.                 bw.close();  
  32.             } catch (IOException e) {  
  33.                 e.printStackTrace();  
  34.             }  
  35.         }  
  36.     } 

相關推薦

java 4方式讀取配置檔案 + 修改配置檔案

方式一:採用ServletContext讀取,讀取配置檔案的realpath,然後通過檔案流讀取出來。 因為是用ServletContext讀取檔案路徑,所以配置檔案可以放入在web-info的classes目錄中,也可以在應用層級及web-info的目錄中。檔案存放位置具

springBoot使用Controller讀取配置檔案方式&讀取自定義配置方法

Controller 核心配置檔案 application.propertie web.msg=Hello! This is Controller demo; Controller:

Java解析xml檔案4方式

java解析xml分為兩類,4種,分別為SAX解析,dom解析,jdom,dom4j.以下具體舉例使用4種方式來實現對一個.xml檔案進行解析: 有命名為dome.xml的檔案, <?xml version="1.0" encoding="UTF-8"?> &l

Java配置方式讀取外部的資源配置文件

eba hsi ptp vlt uwp img dbm woe fsp 通過@PropertySource可以指定讀取的配置文件,通過@Value註解獲取值,具體用法: package cn.qlq; import org.springframework.con

java復制文件的4方式

date family gpo exceptio 處理 nio use 效率 read 一、使用FileStreams復制 這是最經典的方式將一個文件的內容復制到另一個文件中。 使用FileInputStream讀取文件A的字節,使用FileOutputStream寫入到文

java web前端發送請求的4方式

adduser nbsp NPU ajax class servle 表單提交 參數 user 表單 action, 鏈接href,js 綁定按鈕 ajax綁定標簽 <h1>通過表單提交參數</h1> <form acti

Go語言三方式讀取檔案效率對比及原因分析

最近有遇到需要用go讀取大檔案的情況,順路研究了一下go幾種讀取檔案方式的效率。 go幾種常見的檔案io方式 使用os包內的open和read。 fi, err := os.Open(path) // 開啟檔案 buf := make([]byte, 102

spring配置資料來源的4方式以及Druid連線池

第一種:使用spring自帶的DriverManagerDataSource(無連線池的作用) <bean id="dataSource" class="org.springframework

Java建立執行緒的4方式及優缺點

目錄 1. 通過繼承Thread類實現 2. 通過實現Runnable介面實現 3. 通過lambda的方式實現 4. 通過Callable和Future建立執行緒  5. 通過繼承Thread類實現 程式碼展示  6. 通過實現Runnable介面實

Android介面設計的4方式之二——在Java程式碼中控制UI介面

使用者介面設計是Android應用開發中最基本也是最重要的內容,在設計使用者介面時,首先需要了解介面中的UI元素如何呈現給使用者,也就是如何控制UI介面。在Android中提供了4種控制UI介面的方法,下面分別進行介紹。 Android介面概述 在Andro

Java 4陣列複製方式的效能比較

package com.demo.main; import java.util.Arrays; /** * <ol>複製陣列的4種方法 * <li>for</li> * <li>clone</li&

Java實現poi方式讀取word檔案內容(不帶格式)

宣告:文章為原創,程式碼也是經過網上查詢整理的,如有雷同,合情合理,博主很誠實。 1.此技術分享實現Java程式從word文件中讀取文字內容儲存為字串,很簡單。 2.準備工作:poi的jar包,我用的是3.16版本,官網上下載就可以,找不到的可以留言聯絡我。

JAVA用DOM方式讀取xml檔案

Status.xml<?xml version="1.0" encoding="UTF-8"?><StatuList>    <Statu id="1">        <id>1</id>        <n

java方式實現檔案的上傳

1: 實現檔案的上傳可以有好多途徑,最簡單的就是用sun公司提供的File類,可以簡單的實現檔案的上傳和顯示:           try {             InputStream stream = file.getInputStream();//把檔案讀入  

Java建立物件的4方式

使用new關鍵字 通過new關鍵字直接在堆記憶體上建立物件,這樣很方便的呼叫物件的有參和無參的建構函式 Student stu

提交表單的4方式

demo1 doc type function pat 相對 dem location cti 1,超鏈接 <!-- 鏈接到page2 --> <a href="page2.jsp">鏈接到page2</a><br> <

sqoop提供數據庫密碼的4方式

d參數 指定 裏的 路徑 定時 cdh5 als http 並不會 背景 sqoop是一個用來將Hadoop和關系型數據庫(RDBMS)中的數據進行相互轉移的工具。在使用sqoop時,我們需要提供數據庫的訪問密碼。目前sqoop共支持4種輸入密碼的方式: 明文模式。 交互

Docker容器進入的4方式

docker容器進入的4種方式在使用Docker創建了容器之後,大家比較關心的就是如何進入該容器了,其實進入Docker容器有好幾多種方式,這裏我們就講一下常用的幾種進入Docker容器的方法。進入Docker容器比較常見的幾種做法如下:使用docker attach使用SSH使用nsenter使用exec一

java方式實現字符流文件的拷貝對比

put In exception bytes public 字節緩沖區 tput code cep 將D:\\應用軟件\\vm.exe 拷貝到C:\\vm.exe 四種方法耗費時間對比 4>2>3>1 package Copy; imp

java 4修飾符

都是 修飾符 創建 java default ava 訪問權限 權限 fault      訪問權限 類 包 子類 其他包      public ∨ ∨ ∨ ∨ (對任何人都是可用的)      pro