javaweb读取配置文件的4种方法

方式一:采用ServletContext读取

获取配置文件的realpath,然后通过文件流读取出来或者通过方法getReasurceAsStream()。

因为是用ServletContext读取文件路径,所以配置文件可以放入在WEB-INFclasses目录中,也可以在应用层级及WEB-INF的目录中。文件存放位置具体在eclipse工程中的表现是:可以放在src下面,也可放在WEB-INFWeb-Root下面等。因为是读取出路径后,用文件流进行读取的,所以可以读取任意的配置文件包括xmlproperties。缺点:不能在servlet外面应用读取配置信息。

1.首先创建一个动态的javaweb项目,项目目录如下:


2.创建一个servlet(FileReader.java)

[java]  view plain  copy
  1. package com.xia.fileReader;  
  2.   
  3. import java.io.FileInputStream;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.InputStreamReader;  
  7. import java.text.MessageFormat;  
  8. import java.util.Properties;  
  9.   
  10. import javax.servlet.ServletException;  
  11. import javax.servlet.http.HttpServlet;  
  12. import javax.servlet.http.HttpServletRequest;  
  13. import javax.servlet.http.HttpServletResponse;  
  14.   
  15.   
  16.   
  17. public class FileReader extends HttpServlet {  
  18.     private static final long serialVersionUID = 1L;  
  19.     
  20.   
  21.     protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  22.           
  23.          /** 
  24.          * response.setContentType("text/html;charset=UTF-8");目的是控制浏览器用UTF-8进行解码; 
  25.          * 这样就不会出现中文乱码了 
  26.          */  
  27.         response.setHeader("content-type","text/html;charset=UTF-8");  
  28.         readSrcDirPropCfgFile(response);//读取src目录下的db1.properties配置文件  
  29.         response.getWriter().println("<hr/>");  
  30.         readWebRootDirPropCfgFile(response);//读取WebRoot目录下的db2.properties配置文件  
  31.         response.getWriter().println("<hr/>");  
  32.         readSrcSourcePackPropCfgFile(response);//读取src目录下的config目录中的db3.properties配置文件  
  33.         response.getWriter().println("<hr/>");  
  34.         readWEBINFPropCfgFile(response);//读取WEB-INF目录下的JDBC目录中的db4.properties配置文件  
  35.           
  36.     }  
  37.     public void readSrcDirPropCfgFile(HttpServletResponse response) throws IOException {  
  38.         String path = "/WEB-INF/classes/db1.properties";  
  39.         InputStream in = this.getServletContext().getResourceAsStream(path);  
  40.         Properties props = new Properties();  
  41.         props.load(in);  
  42.         String driver = props.getProperty("jdbc.driver");  
  43.         String url = props.getProperty("jdbc.url");  
  44.         String username = props.getProperty("jdbc.username");  
  45.         String password = props.getProperty("jdbc.password");  
  46.         response.getWriter().println("读取src目录下的db1.properties配置文件");  
  47.         response.getWriter().println(MessageFormat.format( "driver={0},url={1},username={2},password={3}",   
  48.                 driver,url, username, password));  
  49.     }  
  50.     public void readWebRootDirPropCfgFile(HttpServletResponse response) throws IOException{  
  51.         String path = "/db2.properties";  
  52.         InputStream in = this.getServletContext().getResourceAsStream(path);  
  53.         Properties props = new Properties();  
  54.         props.load(in);  
  55.         String driver = props.getProperty("jdbc.driver");  
  56.         String url = props.getProperty("jdbc.url");  
  57.         String username = props.getProperty("jdbc.username");  
  58.         String password = props.getProperty("jdbc.password");  
  59.         response.getWriter().println("读取WebRoot目录下的db2.properties配置文件");  
  60.         response.getWriter().println(MessageFormat.format( "driver={0},url={1},username={2},password={3}",   
  61.                 driver,url, username, password));  
  62.     }  
  63.     public void readSrcSourcePackPropCfgFile(HttpServletResponse response) throws IOException {  
  64.         String path = "/WEB-INF/classes/config/db3.properties";  
  65.         String realPath = this.getServletContext().getRealPath(path);  
  66.         InputStreamReader reader = new InputStreamReader(new FileInputStream(realPath),"UTF-8");  
  67.         Properties props = new Properties();  
  68.         props.load(reader);  
  69.         String driver = props.getProperty("jdbc.driver");  
  70.         String url = props.getProperty("jdbc.url");  
  71.         String username = props.getProperty("jdbc.username");  
  72.         String password = props.getProperty("jdbc.password");  
  73.         response.getWriter().println("读取src目录下的config目录中的db3.properties配置文件");  
  74.         response.getWriter().println(MessageFormat.format( "driver={0},url={1},username={2},password={3}",   
  75.                 driver,url, username, password));  
  76.     }  
  77.           
  78.         public void readWEBINFPropCfgFile(HttpServletResponse response) throws IOException {  
  79.         String path = "/WEB-INF/JDBC/db4.properties";  
  80.         String realPath = this.getServletContext().getRealPath(path);  
  81.         System.out.println("realPath:"+realPath);  
  82.         System.out.println("contextPath:"+this.getServletContext().getContextPath());  
  83.         InputStreamReader reader = new InputStreamReader(new FileInputStream(realPath),"UTF-8");  
  84.         Properties props = new Properties();  
  85.         props.load(reader);  
  86.         String driver = props.getProperty("jdbc.driver");  
  87.         String url = props.getProperty("jdbc.url");  
  88.         String username = props.getProperty("jdbc.username");  
  89.         String password = props.getProperty("jdbc.password");  
  90.         response.getWriter().println("读取WEB-INF目录下的JDBC目录中的db4.properties配置文件");  
  91.         response.getWriter().println(MessageFormat.format( "driver={0},url={1},username={2},password={3}",   
  92.                 driver,url, username, password));  
  93.     }  
  94.   
  95.     protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {  
  96.     }  
  97.   
  98. }  

3.配置servlet(web.xml)

[html]  view plain  copy
  1. <?xml version="1.0" encoding="UTF-8"?>  
  2. <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">  
  3.   <display-name>javaReaderFile</display-name>  
  4.   <welcome-file-list>  
  5.     <welcome-file>index.html</welcome-file>  
  6.     <welcome-file>index.htm</welcome-file>  
  7.     <welcome-file>index.jsp</welcome-file>  
  8.     <welcome-file>default.html</welcome-file>  
  9.     <welcome-file>default.htm</welcome-file>  
  10.     <welcome-file>default.jsp</welcome-file>  
  11.   </welcome-file-list>  
  12.     
  13.   <servlet>  
  14.     <servlet-name>FileReader</servlet-name>  
  15.     <servlet-class>com.xia.fileReader.FileReader</servlet-class>  
  16.   </servlet>  
  17.   
  18.   <servlet-mapping>  
  19.     <servlet-name>FileReader</servlet-name>  
  20.     <url-pattern>/FileReader</url-pattern>  
  21.   </servlet-mapping>  
  22. </web-app>  
4.测试


方式二:采用ResourceBundle类读取配置信息

优点是:可以以完全限定类名的方式加载资源后,直接的读取出来,且可以在非Web应用中读取资源文件。

缺点:只能加载类src下面的资源文件且只能读取.properties文件。

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  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. public static 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应用中读取配置资源信息,可以读取任意的资源文件信息
 缺点:只能加载类src下面的资源文件,不适合装载大文件,否则会导致jvm内存溢出
[java]  view plain  copy
  1. package com.xia.fileReader;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.InputStreamReader;  
  7. import java.util.Properties;  
  8.   
  9. public class ReadByClassLoader {  
  10.   
  11.     public static void main(String[] args) throws IOException {  
  12.         readPropFileByClassLoad();  
  13.     }  
  14.   
  15.      public static void readPropFileByClassLoad() throws IOException{  
  16.          //读取src下面config包内的配置文件db3.properties  
  17.          InputStream in = ReadByClassLoader.class.getClassLoader().getResourceAsStream("config/db3.properties");  
  18.          BufferedReader br = new BufferedReader(new InputStreamReader(in));  
  19.          Properties props = new Properties();  
  20.          props.load(br);  
  21.          for(Object s: props.keySet()){  
  22.              System.out.println(s+":"+props.getProperty(s.toString()));  
  23.          }  
  24.      }  
  25. }  

方式四: PropertiesLoaderUtils工具类

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.  * Spring 提供的 PropertiesLoaderUtils 允许您直接通过基于类路径的文件地址加载属性资源 
  3.  * 最大的好处就是:实时加载配置文件,修改后立即生效,不必重启 
  4.  */  
  5. private static void 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.           
  18.         try {Thread.sleep(5000);} catch (InterruptedException e) {e.printStackTrace();}  
  19.     }  

修改Properties

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. /** 
  2.      * 传递键值对的Map,更新properties文件 
  3.      *  
  4.      * @param fileName 
  5.      *            文件名(放在resource源包目录下),需要后缀 
  6.      * @param keyValueMap 
  7.      *            键值对Map 
  8.      */  
  9.     public static void 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.   
  16.         try {  
  17.             filePath = URLDecoder.decode(filePath,"utf-8");      
  18.             log.debug("updateProperties propertiesPath:" + filePath);  
  19.             props = PropertiesLoaderUtils.loadProperties(new ClassPathResource(fileName));  
  20.             log.debug("updateProperties old:"+props);  
  21.               
  22.             // 写入属性文件  
  23.             bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(filePath)));  
  24.               
  25.             props.clear();// 清空旧的文件  
  26.               
  27.             for (String key : keyValueMap.keySet())  
  28.                 props.setProperty(key, keyValueMap.get(key));  
  29.               
  30.             log.debug("updateProperties new:"+props);  
  31.             props.store(bw, "");  
  32.         } catch (IOException e) {  
  33.             log.error(e.getMessage());  
  34.         } finally {  
  35.             try {  
  36.                 bw.close();  
  37.             } catch (IOException e) {  
  38.                 e.printStackTrace();  
  39.             }  
  40.         }  
  41.     }  
版权声明:本文为博主原创文章,未经博主允许不得转载。 http://blog.csdn.net/xnf1991/article/details/52776405
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值