JavaWeb读取配置文件的四种方法

所属分类: 软件编程 / java 阅读数: 17
收藏 0 赞 0 分享

方式一:采用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)

<?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类读取配置信息

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

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

/** 
 * 获取指定配置文件中所有的数据 
 * @param propertyName 
 * 调用方式: 
 * 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方式进行读取配置信息

优点是:可以在非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())); 
 } 
 } 
} 

方式四: 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对路径信息进行了编码,当路径中存在中文和空格时,他会对这些字符进行转换,这样, 
 //得到的往往不是我们想要的真实路径,在此,调用了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(); 
 } 
 } 
 } 

以上所述是小编给大家介绍的JavaWeb读取配置文件的四种方法,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对脚本之家网站的支持!

更多精彩内容其他人还在看

Java数据类型的规则

这篇文章主要介绍了Java数据类型的规则的相关资料,非常不错,具有参考借鉴价值,需要的朋友可以参考下
收藏 0 赞 0 分享

Spring整合TimerTask实现定时任务调度

这篇文章主要介绍了Spring整合TimerTask实现定时任务调度的相关资料,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

详解SpringMVC使用MultipartFile实现文件的上传

本篇文章主要介绍了SpringMVC使用MultipartFile实现文件的上传,本地的文件上传到资源服务器上,比较好的办法就是通过ftp上传。这里是结合SpringMVC+ftp的形式上传的,有兴趣的可以了解一下。
收藏 0 赞 0 分享

SpringMVC上传文件的三种实现方式

本篇文章主要介绍了SpringMVC上传文件的三种实现方式,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

微信公众帐号开发-自定义菜单的创建及菜单事件响应的实例

本篇文章主要介绍了微信公众帐号开发-自定义菜单的创建及菜单事件响应的实例,具有一定的参考价值,感兴趣的小伙伴们可以参考一下。
收藏 0 赞 0 分享

浅析Java中的继承与组合

本文将介绍组合和继承的概念及区别,并从多方面分析在写代码时如何进行选择。文中通过示例代码介绍的很详细,有需要的朋友可以参考借鉴,下面来一起看看吧。
收藏 0 赞 0 分享

利用反射获取Java类中的静态变量名及变量值的简单实例

下面小编就为大家带来一篇利用反射获取Java类中的静态变量名及变量值的简单实例。小编觉得挺不错的,现在就分享给大家,也给大家做个参考。一起跟随小编过来看看吧
收藏 0 赞 0 分享

java启动线程的3种方式对比分析

这篇文章主要为大家对比分析了java启动线程的3种方式,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

SpringMVC上传和解析Excel方法

这篇文章主要介绍了SpringMVC上传和解析Excel方法,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享

JAVA中String类与StringBuffer类的区别

这篇文章主要为大家详细介绍了JAVA中String类与StringBuffer类的区别,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
收藏 0 赞 0 分享
查看更多