JavaWeb讀取配置文件的四種方法
方式一:采用ServletContext讀取
獲取配置文件的realpath,然后通過文件流讀取出來或者通過方法getReasurceAsStream()。
因為是用ServletContext讀取文件路徑,所以配置文件可以放入在WEB-INF的classes目錄中,也可以在應用層級及WEB-INF的目錄中。文件存放位置具體在eclipse工程中的表現(xiàn)是:可以放在src下面,也可放在WEB-INF及Web-Root下面等。因為是讀取出路徑后,用文件流進行讀取的,所以可以讀取任意的配置文件包括xml和properties。缺點:不能在servlet外面應用讀取配置信息。
1.首先創(chuàng)建一個動態(tài)的javaweb項目,項目目錄如下:
2.創(chuàng)建一個servlet(FileReader.java)
package com.xia.fileReader; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.text.MessageFormat; import java.util.Properties; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; public class FileReader extends HttpServlet { private static final long serialVersionUID = 1L; protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /** * response.setContentType("text/html;charset=UTF-8");目的是控制瀏覽器用UTF-8進行解碼; * 這樣就不會出現(xiàn)中文亂碼了 */ response.setHeader("content-type","text/html;charset=UTF-8"); readSrcDirPropCfgFile(response);//讀取src目錄下的db1.properties配置文件 response.getWriter().println("<hr/>"); readWebRootDirPropCfgFile(response);//讀取WebRoot目錄下的db2.properties配置文件 response.getWriter().println("<hr/>"); readSrcSourcePackPropCfgFile(response);//讀取src目錄下的config目錄中的db3.properties配置文件 response.getWriter().println("<hr/>"); readWEBINFPropCfgFile(response);//讀取WEB-INF目錄下的JDBC目錄中的db4.properties配置文件 } public void readSrcDirPropCfgFile(HttpServletResponse response) throws IOException { String path = "/WEB-INF/classes/db1.properties"; InputStream in = this.getServletContext().getResourceAsStream(path); Properties props = new Properties(); props.load(in); String driver = props.getProperty("jdbc.driver"); String url = props.getProperty("jdbc.url"); String username = props.getProperty("jdbc.username"); String password = props.getProperty("jdbc.password"); response.getWriter().println("讀取src目錄下的db1.properties配置文件"); response.getWriter().println(MessageFormat.format( "driver={0},url={1},username={2},password={3}", driver,url, username, password)); } public void readWebRootDirPropCfgFile(HttpServletResponse response) throws IOException{ String path = "/db2.properties"; InputStream in = this.getServletContext().getResourceAsStream(path); Properties props = new Properties(); props.load(in); String driver = props.getProperty("jdbc.driver"); String url = props.getProperty("jdbc.url"); String username = props.getProperty("jdbc.username"); String password = props.getProperty("jdbc.password"); response.getWriter().println("讀取WebRoot目錄下的db2.properties配置文件"); response.getWriter().println(MessageFormat.format( "driver={0},url={1},username={2},password={3}", driver,url, username, password)); } public void readSrcSourcePackPropCfgFile(HttpServletResponse response) throws IOException { String path = "/WEB-INF/classes/config/db3.properties"; String realPath = this.getServletContext().getRealPath(path); InputStreamReader reader = new InputStreamReader(new FileInputStream(realPath),"UTF-8"); Properties props = new Properties(); props.load(reader); String driver = props.getProperty("jdbc.driver"); String url = props.getProperty("jdbc.url"); String username = props.getProperty("jdbc.username"); String password = props.getProperty("jdbc.password"); response.getWriter().println("讀取src目錄下的config目錄中的db3.properties配置文件"); response.getWriter().println(MessageFormat.format( "driver={0},url={1},username={2},password={3}", driver,url, username, password)); } public void readWEBINFPropCfgFile(HttpServletResponse response) throws IOException { String path = "/WEB-INF/JDBC/db4.properties"; String realPath = this.getServletContext().getRealPath(path); System.out.println("realPath:"+realPath); System.out.println("contextPath:"+this.getServletContext().getContextPath()); InputStreamReader reader = new InputStreamReader(new FileInputStream(realPath),"UTF-8"); Properties props = new Properties(); props.load(reader); String driver = props.getProperty("jdbc.driver"); String url = props.getProperty("jdbc.url"); String username = props.getProperty("jdbc.username"); String password = props.getProperty("jdbc.password"); response.getWriter().println("讀取WEB-INF目錄下的JDBC目錄中的db4.properties配置文件"); response.getWriter().println(MessageFormat.format( "driver={0},url={1},username={2},password={3}", driver,url, username, password)); } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { } }
3.配置servlet(web.xml)
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <display-name>javaReaderFile</display-name> <welcome-file-list> <welcome-file>index.html</welcome-file> <welcome-file>index.htm</welcome-file> <welcome-file>index.jsp</welcome-file> <welcome-file>default.html</welcome-file> <welcome-file>default.htm</welcome-file> <welcome-file>default.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>FileReader</servlet-name> <servlet-class>com.xia.fileReader.FileReader</servlet-class> </servlet> <servlet-mapping> <servlet-name>FileReader</servlet-name> <url-pattern>/FileReader</url-pattern> </servlet-mapping> </web-app>
4.測試
方式二:采用ResourceBundle類讀取配置信息
優(yōu)點是:可以以完全限定類名的方式加載資源后,直接的讀取出來,且可以在非Web應用中讀取資源文件。
缺點:只能加載類src下面的資源文件且只能讀取.properties文件。
/** * 獲取指定配置文件中所有的數(shù)據(jù) * @param propertyName * 調(diào)用方式: * 1.配置文件放在resource源包下,不用加后綴 * PropertiesUtil.getAllMessage("message"); * 2.放在包里面的 * PropertiesUtil.getAllMessage("com.test.message"); * @return */ public static List<String> getAllMessage(String propertyName) { // 獲得資源包 ResourceBundle rb = ResourceBundle.getBundle(propertyName.trim()); // 通過資源包拿到所有的key Enumeration<String> allKey = rb.getKeys(); // 遍歷key 得到 value List<String> valList = new ArrayList<String>(); while (allKey.hasMoreElements()) { String key = allKey.nextElement(); String value = (String) rb.getString(key); valList.add(value); } return valList; }
方式三:采用ClassLoader方式進行讀取配置信息
優(yōu)點是:可以在非Web應用中讀取配置資源信息,可以讀取任意的資源文件信息
缺點:只能加載類src下面的資源文件,不適合裝載大文件,否則會導致jvm內(nèi)存溢出
package com.xia.fileReader; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.Properties; public class ReadByClassLoader { public static void main(String[] args) throws IOException { readPropFileByClassLoad(); } public static void readPropFileByClassLoad() throws IOException{ //讀取src下面config包內(nèi)的配置文件db3.properties InputStream in = ReadByClassLoader.class.getClassLoader().getResourceAsStream("config/db3.properties"); BufferedReader br = new BufferedReader(new InputStreamReader(in)); Properties props = new Properties(); props.load(br); for(Object s: props.keySet()){ System.out.println(s+":"+props.getProperty(s.toString())); } } }
方式四: PropertiesLoaderUtils工具類
/** * Spring 提供的 PropertiesLoaderUtils 允許您直接通過基于類路徑的文件地址加載屬性資源 * 最大的好處就是:實時加載配置文件,修改后立即生效,不必重啟 */ private static void springUtil(){ Properties props = new Properties(); while(true){ try { props=PropertiesLoaderUtils.loadAllProperties("message.properties"); for(Object key:props.keySet()){ System.out.print(key+":"); System.out.println(props.get(key)); } } catch (IOException e) { System.out.println(e.getMessage()); } try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();} } }
修改Properties
/** * 傳遞鍵值對的Map,更新properties文件 * * @param fileName * 文件名(放在resource源包目錄下),需要后綴 * @param keyValueMap * 鍵值對Map */ public static void updateProperties(String fileName,Map<String, String> keyValueMap) { //getResource方法使用了utf-8對路徑信息進行了編碼,當路徑中存在中文和空格時,他會對這些字符進行轉(zhuǎn)換,這樣, //得到的往往不是我們想要的真實路徑,在此,調(diào)用了URLDecoder的decode方法進行解碼,以便得到原始的中文及空格路徑。 String filePath = PropertiesUtil.class.getClassLoader().getResource(fileName).getFile(); Properties props = null; BufferedWriter bw = null; try { filePath = URLDecoder.decode(filePath,"utf-8"); log.debug("updateProperties propertiesPath:" + filePath); props = PropertiesLoaderUtils.loadProperties(new ClassPathResource(fileName)); log.debug("updateProperties old:"+props); // 寫入屬性文件 bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath))); props.clear();// 清空舊的文件 for (String key : keyValueMap.keySet()) props.setProperty(key, keyValueMap.get(key)); log.debug("updateProperties new:"+props); props.store(bw, ""); } catch (IOException e) { log.error(e.getMessage()); } finally { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } }
總結(jié)
以上所述是小編給大家介紹的JavaWeb讀取配置文件的四種方法,希望對大家有所幫助,如果大家有任何疑問請給我留言,小編會及時回復大家的。在此也非常感謝大家對腳本之家網(wǎng)站的支持!
相關文章
SpringCloud使用Zookeeper作為配置中心的示例
這篇文章主要介紹了SpringCloud使用Zookeeper作為配置中心的示例,幫助大家更好的理解和學習使用SpringCloud,感興趣的朋友可以了解下2021-04-04使用@TableField(updateStrategy=FieldStrategy.IGNORED)遇到的坑記錄
這篇文章主要介紹了使用@TableField(updateStrategy=FieldStrategy.IGNORED)遇到的坑及解決方案,具有很好的參考價值,希望對大家有所幫助,如有錯誤或未考慮完全的地方,望不吝賜教2023-11-11從內(nèi)存模型中了解Java final的全部細節(jié)
關于final關鍵字,它也是我們一個經(jīng)常用的關鍵字,可以修飾在類上、或者修飾在變量、方法上,以此看來定義它的一些不可變性!像我們經(jīng)常使用的String類中,它便是final來修飾的類,并且它的字符數(shù)組也是被final所修飾的。但是一些final的一些細節(jié)你真的了解過嗎2022-03-03SpringBoot集成screw實現(xiàn)數(shù)據(jù)庫文檔生成的代碼示例
數(shù)據(jù)庫設計文檔是項目技術文檔的重要組成部分,Screw 是一款開源的數(shù)據(jù)庫文檔生成工具,它支持多種數(shù)據(jù)庫類型,并能生成豐富格式的文檔,本文將通過一個實際的例子,展示如何使用 Spring Boot 集成 Screw 生成數(shù)據(jù)庫設計文檔2024-07-07SpringBoot+Prometheus+Grafana實現(xiàn)應用監(jiān)控和報警的詳細步驟
這篇文章主要介紹了SpringBoot+Prometheus+Grafana實現(xiàn)應用監(jiān)控和報警的詳細步驟,本文給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2021-02-02