java读取properties配置文件总结

在日常项目开发和学习中,我们不免会经常用到.propeties配置文件,例如数据库c3p0连接池的配置等。而我们经常读取配置文件的方法有以下两种:

(1).使用getResourceAsStream()方法读取配置文件。

(2).使用InputStream()流去读取配置文件。

注意:在使用getResourceAsStream()读取配置文件时,要特别注意配置文件的路径的写法。

this.getClass.getResourceAsStream(fileName)..使用类和资源文件在同一目录下;

this.getclass.getLoader.getResourceAsStream(fileName)..资源文件和classes同级。

下面,我以一个实例来具体讲述分别使用上述两种方法来读取.properties配置文件。

1.项目结构

在项目中,.properties文件的存放路径基本有以上4种,所有在下面的测试中我会用2种方法读取上面的4种不同路径下的.properties文件。(对应上面的4个配置文件)

(1).src下面config.properties包内的配置文件;

  1. name=\u5F20\u4E09
  2. age=23

(2).和使用配置文件位于同一包里面的.properties配置文件;

  1. name=\u674E\u56DB
  2. age=14

(3).src根目录下面的配置文件;

  1. jdbc.driver=com.mysql.jdbc.Driver
  2. jdbc.url=jdbc:mysql://localhost:3306/goods
  3. jdbc.usename=root
  4. jdbc.password=123456

(4).位于另外一个source文件夹里面的配置文件。

  1. dbuser=user
  2. dbpassword=root
  3. database=javaTest

2.java读取properyies配置文件

首先,创建读取.properties的工具类PropertiesUtil.java

代码清单【1】

  1. package read.propertiesFile.test;
  2.  
  3. import java.io.BufferedInputStream;
  4. import java.io.FileInputStream;
  5. import java.io.FileNotFoundException;
  6. import java.io.IOException;
  7. import java.io.InputStream;
  8. import java.text.MessageFormat;
  9. import java.util.Properties;
  10.  
  11. /**
  12. * java读取properties配置文件工具类
  13. * @author Administrator
  14. *
  15. * 2016/12/04
  16. */
  17. public class PropertiesUtil
  18. {
  19. public static final PropertiesUtil INSTANCE = new PropertiesUtil();
  20.  
  21. public static PropertiesUtil getInstance()
  22. {
  23. return INSTANCE;
  24. }
  25. /**
  26. * 1.使用getSourceAsStream读取配置文件
  27. */
  28. public void readPropertiesByGetSourceAsStream()
  29. {
  30. /*
  31. * 1.src下面config.properties包内的配置文件
  32. * test1.properties
  33. */
  34. InputStream is1 = JavaReadPropertiesTest.class.getClassLoader().getResourceAsStream("config/properties/test1.properties");
  35.  
  36. /*
  37. * 2.读取和JavaReadPropertiesTest类位于同一个包里面的配置文件
  38. * test2.properties
  39. */
  40. InputStream is2 = JavaReadPropertiesTest.class.getResourceAsStream("test2.properties");
  41.  
  42. /*
  43. * 3.读取根目录下面的配置文件
  44. * jdbc.properties
  45. */
  46. InputStream is3 = JavaReadPropertiesTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
  47.  
  48. /*
  49. * 4.读取位于另外一个source文件夹里面的配置文件
  50. * config.properties
  51. */
  52. InputStream is4 = JavaReadPropertiesTest.class.getClassLoader().getResourceAsStream("config.properties");
  53. Properties p = new Properties();
  54. System.out.println("使用getSourceAsStream()读取配置文件...");
  55. try
  56. {
  57. System.out.println("---读取is1开始---");
  58. p.load(is1);
  59. System.out.println("test1.properties:name = "+ p.getProperty("name")
  60. + ",age = " + p.getProperty("age"));
  61. System.out.println("---读取is1结束---");
  62. System.out.println("-----------------------------------------------");
  63.  
  64. System.out.println("---读取is2开始---");
  65. p.load(is2);
  66. System.out.println("test2.properties:name = "+ p.getProperty("name")
  67. + ",age = " + p.getProperty("age"));
  68. System.out.println("---读取is2结束---");
  69. System.out.println("-----------------------------------------------");
  70.  
  71. System.out.println("---读取is3开始---");
  72. p.load(is3);
  73. System.out.println("jdbc.properties:");
  74. // 这里的%s是java String占位符
  75. System.out.println(String.format("jdbc.driver=%s",p.getProperty("jdbc.driver")));
  76. System.out.println(String.format("jdbc.url=%s",p.getProperty("jdbc.url")));
  77. System.out.println(String.format("jdbc.usename=%s",p.getProperty("jdbc.usename")));
  78. System.out.println(String.format("jdbc.password=%s",p.getProperty("jdbc.password")));
  79. System.out.println("---读取is3结束---");
  80. System.out.println("-----------------------------------------------");
  81.  
  82. System.out.println("---读取is4开始---");
  83. p.load(is4);
  84. System.out.println(MessageFormat.format("dbuser={0}", p.getProperty("dbuser")));
  85. System.out.println(MessageFormat.format("dbpassword={0}", p.getProperty("dbpassword")));
  86. System.out.println(MessageFormat.format("database={0}", p.getProperty("database")));
  87. System.out.println("---读取is4结束---");
  88. }
  89. catch (IOException e)
  90. {
  91. e.printStackTrace();
  92. }
  93. finally
  94. {
  95. if(null != is1)
  96. {
  97. try {
  98. is1.close();
  99. }
  100. catch (IOException e)
  101. {
  102. e.printStackTrace();
  103. }
  104. }
  105.  
  106. if(null != is2)
  107. {
  108. try {
  109. is2.close();
  110. }
  111. catch (IOException e)
  112. {
  113. e.printStackTrace();
  114. }
  115. }
  116.  
  117. if(null != is3)
  118. {
  119. try {
  120. is3.close();
  121. }
  122. catch (IOException e)
  123. {
  124. e.printStackTrace();
  125. }
  126. }
  127.  
  128. if(null != is4)
  129. {
  130. try {
  131. is4.close();
  132. }
  133. catch (IOException e)
  134. {
  135. e.printStackTrace();
  136. }
  137. }
  138. }
  139. }
  140.  
  141. /**
  142. * 2.使用InputStream读取配置文件
  143. */
  144. public void readPropertiesByInputStream()
  145. {
  146. InputStream is1 = null;
  147. InputStream is2 = null;
  148. InputStream is3 = null;
  149. InputStream is4 = null;
  150. System.out.println("使用InputStream读取配置文件...");
  151. try
  152. {
  153. /*
  154. * 1.src下面config.properties包内的配置文件
  155. * test1.properties
  156. */
  157. is1 = new BufferedInputStream(new FileInputStream("src/config/properties/test1.properties"));
  158.  
  159. /*
  160. * 2.读取和JavaReadPropertiesTest类位于同一个包里面的配置文件
  161. * test2.properties
  162. */
  163. is2 = new BufferedInputStream(new FileInputStream("src/read/propertiesFile/test/test2.properties"));
  164.  
  165. /*
  166. * 3.读取根目录下面的配置文件
  167. * jdbc.properties
  168. */
  169. is3 = new BufferedInputStream(new FileInputStream("src/jdbc.properties"));
  170.  
  171. /*
  172. * 4.读取位于另外一个source文件夹里面的配置文件
  173. * config.properties
  174. */
  175. is4 = new BufferedInputStream(new FileInputStream("config/config.properties"));
  176.  
  177. Properties p = new Properties();
  178.  
  179. System.out.println("---读取is1开始---");
  180. p.load(is1);
  181. System.out.println("test1.properties:name = "+ p.getProperty("name")
  182. + ",age = " + p.getProperty("age"));
  183. System.out.println("---读取is1结束---");
  184. System.out.println("-----------------------------------------------");
  185.  
  186. System.out.println("---读取is2开始---");
  187. p.load(is2);
  188. System.out.println("test2.properties:name = "+ p.getProperty("name")
  189. + ",age = " + p.getProperty("age"));
  190. System.out.println("---读取is2结束---");
  191. System.out.println("-----------------------------------------------");
  192.  
  193. System.out.println("---读取is3开始---");
  194. p.load(is3);
  195. System.out.println("jdbc.properties:");
  196. System.out.println(String.format("jdbc.driver=%s",p.getProperty("jdbc.driver")));
  197. System.out.println(String.format("jdbc.url=%s",p.getProperty("jdbc.url")));
  198. System.out.println(String.format("jdbc.usename=%s",p.getProperty("jdbc.usename")));
  199. System.out.println(String.format("jdbc.password=%s",p.getProperty("jdbc.password")));
  200. System.out.println("---读取is3结束---");
  201. System.out.println("-----------------------------------------------");
  202.  
  203. System.out.println("---读取is4开始---");
  204. p.load(is4);
  205. System.out.println("config.properties:");
  206. System.out.println(MessageFormat.format("bduser={0}", p.getProperty("bduser")));
  207. System.out.println(MessageFormat.format("bdpassword={0}", p.getProperty("bdpassword")));
  208. System.out.println(MessageFormat.format("database={0}", p.getProperty("database")));
  209. System.out.println("---读取is4结束---");
  210.  
  211. }
  212. catch (FileNotFoundException e)
  213. {
  214. e.printStackTrace();
  215. }
  216. catch (IOException e)
  217. {
  218. e.printStackTrace();
  219. }
  220. finally
  221. {
  222. if(null != is1)
  223. {
  224. try {
  225. is1.close();
  226. }
  227. catch (IOException e)
  228. {
  229. e.printStackTrace();
  230. }
  231. }
  232.  
  233. if(null != is2)
  234. {
  235. try {
  236. is2.close();
  237. }
  238. catch (IOException e)
  239. {
  240. e.printStackTrace();
  241. }
  242. }
  243.  
  244. if(null != is3)
  245. {
  246. try {
  247. is3.close();
  248. }
  249. catch (IOException e)
  250. {
  251. e.printStackTrace();
  252. }
  253. }
  254.  
  255. if(null != is4)
  256. {
  257. try {
  258. is4.close();
  259. }
  260. catch (IOException e)
  261. {
  262. e.printStackTrace();
  263. }
  264. }
  265. }
  266. }
  267. }

然后,JUnit测试 JavaReadPropertiesTest.java

代码清单【2】

  1. package read.propertiesFile.test;
  2.  
  3. import org.junit.Test;
  4.  
  5. /**
  6. * java读取properties配置文件
  7. * @author Administrator
  8. *
  9. */
  10.  
  11. public class JavaReadPropertiesTest
  12. {
  13. /**
  14. * 1.使用getSourceAsStream读取配置文件测试
  15. */
  16. @Test
  17. public void readPropertiesByGetSourceAsStreamTest()
  18. {
  19. PropertiesUtil.getInstance().readPropertiesByGetSourceAsStream();
  20. }
  21.  
  22. /**
  23. * 2.使用InputStream读取配置文件测试
  24. */
  25. @Test
  26. public void readPropertiesByInputStreamTest()
  27. {
  28. PropertiesUtil.getInstance().readPropertiesByInputStream();
  29. }
  30.  
  31. }

3.输出结果

  1. 使用getSourceAsStream()读取配置文件...
  2. ---读取is1开始---
  3. test1.properties:name = 张三,age = 23
  4. ---读取is1结束---
  5. -----------------------------------------------
  6. ---读取is2开始---
  7. test2.properties:name = 李四,age = 14
  8. ---读取is2结束---
  9. -----------------------------------------------
  10. ---读取is3开始---
  11. jdbc.properties:
  12. jdbc.driver=com.mysql.jdbc.Driver
  13. jdbc.url=jdbc:mysql://localhost:3306/goods
  14. jdbc.usename=root
  15. jdbc.password=123456
  16. ---读取is3结束---
  17. -----------------------------------------------
  18. ---读取is4开始---
  19. dbuser=user
  20. dbpassword=root
  21. database=javaTest
  22. ---读取is4结束---
  23. 使用InputStream读取配置文件...
  24. ---读取is1开始---
  25. test1.properties:name = 张三,age = 23
  26. ---读取is1结束---
  27. -----------------------------------------------
  28. ---读取is2开始---
  29. test2.properties:name = 李四,age = 14
  30. ---读取is2结束---
  31. -----------------------------------------------
  32. ---读取is3开始---
  33. jdbc.properties:
  34. jdbc.driver=com.mysql.jdbc.Driver
  35. jdbc.url=jdbc:mysql://localhost:3306/goods
  36. jdbc.usename=root
  37. jdbc.password=123456
  38. ---读取is3结束---
  39. -----------------------------------------------
  40. ---读取is4开始---
  41. config.properties:
  42. bduser=null
  43. bdpassword=null
  44. database=javaTest
  45. ---读取is4结束---

4.补充

在这里,我在简要介绍一下,读取配置文件的全部配置信息的方法,以jdbc.properties文件为例。

  1. /**
  2. * 3.循环读取配置文件的全部信息
  3. */
  4. public void readAllInfo()
  5. {
  6. /*
  7. * 3.读取根目录下面的配置文件
  8. * jdbc.properties
  9. */
  10. InputStream is3 = JavaReadPropertiesTest.class.getClassLoader().getResourceAsStream("jdbc.properties");
  11. Properties p = new Properties();
  12. System.out.println("---读取is3开始---");
  13. try
  14. {
  15. p.load(is3);
  16. //读取资源文件的所有的key值
  17. Enumeration en= p.propertyNames();
  18. System.out.println("读取is3开始...");
  19. while(en.hasMoreElements())
  20. {
  21. String key = (String) en.nextElement();
  22. System.out.println(key + "=" + p.getProperty(key));
  23.  
  24. }
  25. System.out.println("读取is3结束...");
  26. }
  27. catch (IOException e)
  28. {
  29. e.printStackTrace();
  30. System.out.println("读取资源文件出错");
  31. }
  32. finally
  33. {
  34. if(null != is3)
  35. {
  36. try
  37. {
  38. is3.close();
  39. System.out.println("关闭is3...");
  40. }
  41. catch (IOException e)
  42. {
  43. e.printStackTrace();
  44. }
  45. }
  46. }
  47.  
  48. }

输出结果是:

  1. ---读取is3开始---
  2. 读取is3开始...
  3. jdbc.url=jdbc:mysql://localhost:3306/goods
  4. jdbc.driver=com.mysql.jdbc.Driver
  5. jdbc.usename=root
  6. jdbc.password=123456
  7. 读取is3结束...
  8. 关闭is3...

至此,读取配置文件的总结就先这样,后期有新的体会时,在进行增加。谢谢观阅。

java读取properties配置文件总结的更多相关文章

  1. java读取properties配置文件信息

    一.Java Properties类 Java中有个比较重要的类Properties(Java.util.Properties),主要用于读取Java的配置文件,各种语言都有自己所支持的配置文件,配置 ...

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

    Java 开发中,需要将一些易变的配置参数放置再 XML 配置文件或者 properties 配置文件中.然而 XML 配置文件需要通过 DOM 或 SAX 方式解析,而读取 properties 配 ...

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

    读取.properties配置文件在实际的开发中使用的很多,总结了一下,有以下几种方法(仅仅是我知道的):一.通过jdk提供的java.util.Properties类.此类继承自java.util. ...

  4. Java 读取 .properties 配置文件

    java 开发中,经常要读取 properties 配置文件,下面介绍几种读取方式: 1.基于 InputStream 读取配置文件 该方式的优点在于可以读取任意路径下的配置文件 Properties ...

  5. Java读取properties配置文件工具类

    1.   PropertyUtils.java package javax.utils; import java.io.InputStream; import java.util.Properties ...

  6. 【转载】java读取.properties配置文件的几种方法

    读取.properties配置文件在实际的开发中使用的很多,总结了一下,有以下几种方法(仅仅是我知道的):一.通过jdk提供的java.util.Properties类.此类继承自java.util. ...

  7. Java读取Properties配置文件

    1.Properties类与Properties配置文件 Properties类继承自Hashtable类并且实现了Map接口,使用键值对的形式来保存属性集.不过Properties的键和值都是字符串 ...

  8. java读取properties配置文件的方法

    app.properties mail.smtp.host=smtp.163.com mail.transport.protocol=smtp import java.io.InputStream; ...

  9. Java读取.properties配置文件并连接数据库

    1.读取配置文件 //Properties集合 流对象读取键值对 public static void getNum() throws Exception { Properties p=new Pro ...

随机推荐

  1. YII2学习第一天

    YII2学习第一天,之前稍微看了看TP,感觉和自己的理念不是很符合,然后转学YII2了. 使用的文档是https://github.com/yiisoft/yii2/tree/master/docs/ ...

  2. 循序渐进Python3(十一) --5-- 同源策略

    一.什么是同源策略 同源策略(Same origin policy)是一种约定,它是浏览器最核心也最基本的安全功能.它是由Netscape提出的一个著名的安全策略,现在所有的可支持javascript ...

  3. Linux 常用命令 :cd命令

    ls命令是linux下最常用的命令.ls命令就是list的缩写缺省下ls用来打印出当前目录的清单如果ls指定其他目录那么就会显示指定目录里的文件及文件夹清单. 通过ls 命令不仅可以查看linu ...

  4. python动态获取对象的属性和方法 (转载)

    首先通过一个例子来看一下本文中可能用到的对象和相关概念. #coding:utf-8 import sys def foo():pass class Cat(object): def __init__ ...

  5. 使用miniui框架制作树形节点

    <div id="leftTree" class="mini-outlooktree" url="<%=basePath%>mana ...

  6. Shell学习笔记 - 环境变量配置文件(转)

    一.source命令 功能:在当前bash环境下读取并执行配置文件中的命令 1. 命令格式 source 配置文件  或  . 配置文件 2. 命令示例 [root@localhost ~]# sou ...

  7. C++函数重载和函数模板

    1.函数重载 这是小菜鸟写的一个例子. 函数重载应该注意以下几点: 1.1重载函数有类似的功能: 1.2只能以参数的类型(形参个数和类型)来重载函数, int max(int a,int b);flo ...

  8. CodeFirst进行数据迁移之添加字段

    一.为模型更改设置 Code First 数据迁移 1.工具->库程序包管理器->程序包管理器控制台->输入"Enable-Migrations"  或者 Ena ...

  9. mysql 计算日期差

    有两个途径可获得   1.利用TO_DAYS函数   select to_days(now()) - to_days('20140831')   2.利用DATEDIFF函数   select dat ...

  10. java多线程详解(4)-多线程同步技术与lock

    前言:本篇文章是对Synchronized和java.util.concurrent.locks.Lock的区别进行了详细的分析介绍 上一篇文章末最后介绍了synchronized的一些缺陷,本文主要 ...