版权声明:本文为博主原创文章,未经博主允许不得转载。

 
 

方式一:采用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 4种方式读取配置文件 + 修改配置文件的更多相关文章

  1. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件

    精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件 内容简介:本文介绍 Spring Boot 的配置文件和配置管理,以及介绍了三种读取配置文 ...

  2. 远程访问Jupyter Notebook的两种方式:命令行和配置文件

    远程访问Jupyter Notebook的两种方式:命令行和配置文件 相关配置:Ubuntu 16.04服务器,本地Win10,使用了Xshell,Xftp工具. 相关配置主要分为三步: 服务器上的J ...

  3. 将图片base64格式转换为file对象并读取(两种方式读取)

    两种方式读取,一种URL.createObjectURL,另一种fileReader   var base64 = ` data:image/jpeg;base64,/9j/4AAQSkZJRgABA ...

  4. java web工程读取及修改配置文件

    这篇博客比自己讲解的详细: http://blog.sina.com.cn/s/blog_69398ed9010191jg.html 使用方法: 1)配置文件在web-info的class目录下,或者 ...

  5. 第二种方式读取并显示HDFS中的内容

    1.讀取HDFS内容的java客戶端代碼: package Hdfs; import java.io.InputStream; import java.net.URI; import org.apac ...

  6. Java两种方式简单实现:爬取网页并且保存

    注:如果代码中有冗余,错误或者不规范,欢迎指正. Java简单实现:爬取网页并且保存 对于网络,我一直处于好奇的态度.以前一直想着写个爬虫,但是一拖再拖,懒得实现,感觉这是一个很麻烦的事情,出现个小错 ...

  7. 用类加载器的5种方式读取.properties文件

    用类加载器的5中形式读取.properties文件(这个.properties文件一般放在src的下面) 用类加载器进行读取:这里采取先向大家讲读取类加载器的几种方法:然后写一个例子把几种方法融进去, ...

  8. C# 读取与修改配置文件

    System.Configuration.ConfigurationSettings.AppSettings["Key"]; 但是现在FrameWork2.0已经明确表示此属性已经 ...

  9. .net core 读取、修改配置文件appsettings.json

    .net core 设置读取JSON配置文件 appsettings.json Startup.cs 中 public class Startup { public Startup(IHostingE ...

随机推荐

  1. WPF 线程 Dispatcher

    WPF 应用程序从两个线程开始: 一个用于处理呈现 一个用于管理 UI 呈现线程有效地隐藏在后台运行,而UI线程则接收输入.处理事件.绘制屏幕以及运行应用程序代码. 大多数应用程序都使用一个 UI 线 ...

  2. Sql Server 2008服务启动失败,错误17058

    SQL Server (SQLEXPRESS) 服务因 17058 (0x42A2) 服务性错误而停止. 有关更多信息,请参阅在 http://go.microsoft.com/fwlink/even ...

  3. poj1988_Cube Stacking

    Cube Stacking Time Limit: 2000MS   Memory Limit: 30000K Total Submissions: 24130   Accepted: 8468 Ca ...

  4. [mysql]知识补充

    知识概况 视图 函数 存储过程 事务 索引 触发器 [视图] 视图是一个虚拟表,可以实现查询功能,不能进行增删改 本质:根据sql语句获取动态的数据集,并为其命名 1.创建视图 --create vi ...

  5. iOS之ToolBar定制

    ToorBar的定制 在诸如社区类的app里面,很多都涉及到用户发布消息,如现今最流行的新浪微博,每条信息底部都会有个工具条,正如下图所示,有转发.评论和点赞三个按钮的工具条. 结构 1.作为一个独立 ...

  6. python--基础学习(五)参数位置传递、关键字传递、包裹传递及解包裹

    python系列均基于python3.4环境 1.位置传递和关键字传递 代码示例 #位置传递 def fun(a,b,c): print("a: {0}, b: {1}, c: {2}&qu ...

  7. 事务日志以及虚拟日志文件(VLFs)概述

    Part 1:事务日志 每个 SQL Server 数据库都具有事务日志,用于记录所有事务以及每个事务对数据库所做的修改.必须定期截断事务日志以避免它被填满.但是,一些因素可能延迟日志截断,因此监视日 ...

  8. 根据google地图抓去全国信息- 抓去全国小区以及新建楼盘信息

    本案例由于google每天每个账户能post20000次所以我们需要相对较长的时间来抓去google的数据信息. 主要思路:通过一定的zoom一个相对较大的zoom.我们尽可能的搜索我们的所有数据. ...

  9. android中设置控件获得焦点 (转)

    android中,要使控件获得焦点,需要先setFocus,再requestFocus. 以Button为例:                 btn.setFocusable(true);      ...

  10. hdu 4717(三分求极值)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4717 思路:三分时间求极小值. #include <iostream> #include ...