转载:http://blog.csdn.net/gaogaoshan/article/details/8605887

 
 

方式一:采用ServletContext读取,读取配置文件的realpath,然后通过文件流读取出来。

因为是用ServletContext读取文件路径,所以配置文件可以放入在web-info的classes目录中,也可以在应用层级及web-info的目录中。文件存放位置具体在eclipse工程中的表现是:可以放在src下面,也可放在web-info及webroot下面等。因为是读取出路径后,用文件流进行读取的,所以可以读取任意的配置文件包括xml和properties。缺点:不能在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. 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应用中读取配置资源信息,可以读取任意的资源文件信息
 缺点:只能加载类classes下面的资源文件。
  1. /**获取的是class的根路径下的文件
  2. * 优点是:可以在非Web应用中读取配置资源信息,可以读取任意的资源文件信息
  3. * 缺点:只能加载类classes下面的资源文件。
  4. * 如果要加上路径的话:com/test/servlet/jdbc_connection.properties
  5. */
  6. private static void 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. 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. 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. 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. 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读取配置文件(转)的更多相关文章

  1. java读取配置文件的几种方法

    java读取配置文件的几种方法 原文地址:http://hbcui1984.iteye.com/blog/56496         在现实工作中,我们常常需要保存一些系统配置信息,大家一般都会选择配 ...

  2. Java读取配置文件的方式

    Java读取配置文件的方式-笔记 1       取当前启动文件夹下的配置文件   一般来讲启动java程序的时候.在启动的文件夹下会有配置文件 classLoader.getResource(&qu ...

  3. java读取配置文件

    java 读取文件可以用字节流和字符流. 由于一个汉字占两个字节,所以如果配置文件中有汉字,用字节流读取,会出现乱码. 用字符流则不会出现乱码. 配置文件 b.properties 文件如下: fam ...

  4. Java 读取配置文件数据

    Properties类 Properties类,是一个工具类,包含在java.util包中. 功能:可以保存持久的属性,通常用来读取配置文件或者属性文件,将文件中的数据读入properties对象中, ...

  5. java读取配置文件方法以及工具类

    第一种方式 : java工具类读取配置文件工具类 只是案例代码  抓取异常以后的代码自己处理 import java.io.FileNotFoundException; import java.io. ...

  6. java读取配置文件内容

    利用com.typesafe.config包实现 <dependency> <groupId>com.typesafe</groupId> <artifact ...

  7. spring boot使用java读取配置文件,DateSource测试,BomCP测试,AnnotationConfigApplicationContext的DataSource注入

    一.配置注解读取配置文件         (1)@PropertySource可以指定读取的配置文件,通过@Value注解获取值   实例:           @PropertySource(val ...

  8. 使用Java读取配置文件

    实现起来,相对比较简单,留个备案吧,废话也不多说,请看代码: package com.jd.***.config; import org.junit.*; import java.io.IOExcep ...

  9. 转:java读取配置文件的几种方法

    转自: http://www.iteye.com/topic/56496 在现实工作中,我们常常需要保存一些系统配置信息,大家一般都会选择配置文件来完成,本文根据笔者工作中用到的读取配置文件的方法小小 ...

随机推荐

  1. 【转】java与C++的区别

    转自:http://club.topsage.com/thread-265349-1-1.html Java并不仅仅是C++语言的一个变种,它们在某些本质问题上有根本的不同: (1)Java比C++程 ...

  2. 投票ajax请求代码(点赞代码)

    function vote(url, arr) { jq.ajax({ cache: false, async: false, url: url, type: 'post', data: {info_ ...

  3. FIFO、LRU、LFU的含义和原理(转)

    题目:请简要介绍FIFO.LRU.LFU的含义和原理   含义: FIFO:First In First Out,先进先出LRU:Least Recently Used,最近最少使用 LFU:Leas ...

  4. JDBC:数据库操作:BLOB数据处理

    CLOB主要保存海量文字,而BLOB是专门保存二进制数据:包括,图片,音乐,影片.等. 在MYSQL中,BLOB类型使用LONGBLOB声明,最高可存储4G内容. 创建一个表: create tabl ...

  5. CentOS忘记root密码解决办法

    如果是忘记普通的用户密码,那还好说,用root登录命令行界面,修改即可. 但如果是root的话,那就需要这样修改了.   记住,这几篇文章说的都是对的,只是我复杂了,实际只需要将光标移到最后" ...

  6. easyui tree自定义属性用法

    easyui为树显示提供了以下属性, id:节点id,这个很重要到加载远程服务器数据 which is important to load remote data text: 显示的节点文本 stat ...

  7. 中小型研发团队架构实践:分布式协调服务ZooKeeper

    一.ZooKeeper 是什么 Apache ZooKeeper 由 Apache Hadoop 的子项目发展而来,于 2010 年 11 月正式成为了 Apache 的顶级项目. 相关厂商内容 优秀 ...

  8. 零样本学习 - (Zero shot learning,ZSL)

    https://zhuanlan.zhihu.com/p/41846072 https://zhuanlan.zhihu.com/p/38418698 https://zhuanlan.zhihu.c ...

  9. linux释放内存命令

    1.首先查看linux内存使用 #free -m 2.把内存数据同步到硬盘#sync 3.修改 /proc/sys/vm/drop_caches文件 #echo 3 > /proc/sys/vm ...

  10. Java自带命令详解

    1. 背景 给一个系统定位问题的时候,知识.经验是关键基础,数据(运行日志.异常堆栈.GC日志.线程快照[threaddump / javacore文件].堆转储快照[heapdump / hprof ...