javaweb讀取配置檔案的4種方法
阿新 • • 發佈:2018-12-31
方式一:採用ServletContext讀取
獲取配置檔案的realpath,然後通過檔案流讀取出來或者通過方法getReasurceAsStream()。
因為是用ServletContext讀取檔案路徑,所以配置檔案可以放入在WEB-INF的classes目錄中,也可以在應用層級及WEB-INF的目錄中。檔案存放位置具體在eclipse工程中的表現是:可以放在src下面,也可放在WEB-INF及Web-Root下面等。因為是讀取出路徑後,用檔案流進行讀取的,所以可以讀取任意的配置檔案包括xml和properties。缺點:不能在servlet外面應用讀取配置資訊。
1.首先建立一個動態的javaweb專案,專案目錄如下:
2.建立一個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進行解碼; * 這樣就不會出現中文亂碼了 */ 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)
4.測試<?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>
方式二:採用ResourceBundle類讀取配置資訊
優點是:可以以完全限定類名的方式載入資源後,直接的讀取出來,且可以在非Web應用中讀取資原始檔。
缺點:只能載入類src下面的資原始檔且只能讀取.properties檔案。
- /**
- * 獲取指定配置檔案中所有的資料
- * @param propertyName
- * 呼叫方式:
- * 1.配置檔案放在resource源包下,不用加字尾
- * PropertiesUtil.getAllMessage("message");
- * 2.放在包裡面的
- * PropertiesUtil.getAllMessage("com.test.message");
- * @return
- */
- publicstatic 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方式進行讀取配置資訊
優點是:可以在非Web應用中讀取配置資源資訊,可以讀取任意的資原始檔資訊 缺點:只能載入類src下面的資原始檔,不適合裝載大檔案,否則會導致jvm記憶體溢位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包內的配置檔案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()));
}
}
}