• 一文带你全面了解Properties类


    概述

    Properties是JDK1.0中引入的java类,目前也在项目中大量使用,主要用来读取外部的配置,那除了这个,你对它其他的一些api也了解吗? 你了解它是怎么实现的吗? 如果不清楚的话,就通过本篇文章带你一探究竟。

    介绍

    java.util.Properties继承自java.util.Hashtable,是一个持久化的属性保存对象,可以将属性内容写出到stream中或者从stream中读取属性内容。 它的重要特性如下:

    • 在底层的Hashtable中,每一对属性的key和value都是按照string类型来保存的。
    • Properties支持文本方式和xml方式的数据存储。在文本方式中,格式为key:value,其中分隔符可以是:冒号(:)、等号(=)、空格。其中空格可以作为key的结束,同时获取的值回将分割符号两端的空格去掉。
    • Properties可以将其他的Properties对象作为默认的值。
    • Hashtable的所有方法Properties对象均可以访问,但是不建议这么做,因为Hashtable可以存放其他数据类型,这样会导致Properties一些方法调用报错。
    • 在properties文件中,可以用井号"#"来作注释。
    • 线程安全
    • key、value不可以是null

    构造方法

    • Properties()

    创建一个无默认值的空属性列表。

    • Properties(Properties defaults)

    创建一个带有指定默认值的空属性列表。

    关键方法

    • getProperty ( String key)

    根据指定的key获取对应的属性value值,如果在自身的存储集合中没有找到对应的key,那么就直接到默认的defaults属性指定的Properties中获取属性值。

    • getProperty(String, String)

    当getProperty(String)方法返回值为null的时候,返回给定的默认值,而不是返回null。

    • load ( InputStream inStream)

    从byte stream中加载key/value键值对,要求所有的key/value键值对是按行存储,同时是用ISO-8859-1编译的, 不支持中文。

    • load(Reader)

    从字符流中加载key/value键值对,要求所有的键值对都是按照行来存储的。

    • loadFromXML(InputStream)

    从xml文件中加载property,底层使用XMLUtils.load(Properties,InputStream)方法来加载。

    • setProperty ( String key, String value)

    调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。

    • store ( OutputStream out, String comments)

    将所有的property(保存defaults的)都写出到流中,同时如果给定comments的话,那么要加一个注释。

    • storeToXML(OutputSteam, comment, encoding)

    写出到xml文件中。

    • Set stringPropertyNames()

    获取所有Properties中所有的key集合

    • clear ()

    清除所有装载的 键值对。该方法在基类中提供。

    使用案例

    1. 新建配置文件app.properties
    1. ## 用户信息
    2. user.name:旭阳
    3. user.age=28
    4. user.sex 男
    5. 复制代码

    通过idea设置它的格式为UTF-8。

    1. 验证读取以及中文乱码的问题
    1. @Test
    2. public void test1() throws IOException {
    3. Properties properties = new Properties();
    4. // 使用load inputstream
    5. properties.load(this.getClass().getClassLoader().getResourceAsStream("app.properties"));
    6. // 出现乱码
    7. System.out.println(properties);
    8. // 转码
    9. System.out.println(new String(properties.getProperty("user.name").getBytes(StandardCharsets.ISO_8859_1), StandardCharsets.UTF_8));
    10. Properties properties2 = new Properties();
    11. // 使用load read
    12. BufferedReader bf = new BufferedReader(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("app.properties"), "UTF-8"));
    13. properties2.load(bf);
    14. System.out.println(properties2);
    15. }
    16. 复制代码

    运行结果:

    1. 保存为xml格式
    1. @Test
    2. public void test2() throws IOException {
    3. Properties properties2 = new Properties();
    4. // 使用load read
    5. BufferedReader bf = new BufferedReader(new InputStreamReader(this.getClass().getClassLoader().getResourceAsStream("app.properties"), "UTF-8"));
    6. properties2.load(bf);
    7. System.out.println(properties2);
    8. // 保存到xml
    9. FileOutputStream fileOutputStream = new FileOutputStream("app.xml");
    10. properties2.storeToXML(fileOutputStream, "alvin info", "UTF-8");
    11. }
    12. 复制代码

    运行结果:

    源码解析

    源码这部分主要分析下load(Reader)和load(InputStream)这两个最常用的方法,这两个方法是指定从文本文件中加载key/value属性值,底层都是将流封装成为LineReader对象,然后通过load0方法来加载属性键值对的。

    1. public synchronized void load(InputStream inStream) throws IOException {
    2. load0(new LineReader(inStream));
    3. }
    4. 复制代码

    将inputStream封装程一个LineReader,每次可以读取一行数据。

    LineReader源码分析:

    1. class LineReader {
    2. /**
    3. * 根据字节流创建LineReader对象
    4. *
    5. * @param inStream
    6. * 属性键值对对应的字节流对象
    7. */
    8. public LineReader(InputStream inStream) {
    9. this.inStream = inStream;
    10. inByteBuf = new byte[8192];
    11. }
    12. /**
    13. * 根据字符流创建LineReader对象
    14. *
    15. * @param reader
    16. * 属性键值对对应的字符流对象
    17. */
    18. public LineReader(Reader reader) {
    19. this.reader = reader;
    20. inCharBuf = new char[8192];
    21. }
    22. // 字节流缓冲区, 大小为8192个字节
    23. byte[] inByteBuf;
    24. // 字符流缓冲区,大小为8192个字符
    25. char[] inCharBuf;
    26. // 当前行信息的缓冲区,大小为1024个字符
    27. char[] lineBuf = new char[1024];
    28. // 读取一行数据时候的实际读取大小
    29. int inLimit = 0;
    30. // 读取的时候指向当前字符位置
    31. int inOff = 0;
    32. // 字节流对象
    33. InputStream inStream;
    34. // 字符流对象
    35. Reader reader;
    36. /**
    37. * 读取一行,将行信息保存到{@link lineBuf}对象中,并返回实际的字符个数
    38. *
    39. * @return 实际读取的字符个数
    40. * @throws IOException
    41. */
    42. int readLine() throws IOException {
    43. // 总的字符长度
    44. int len = 0;
    45. // 当前字符
    46. char c = 0;
    47. boolean skipWhiteSpace = true;
    48. boolean isCommentLine = false;
    49. boolean isNewLine = true;
    50. boolean appendedLineBegin = false;
    51. boolean precedingBackslash = false;
    52. boolean skipLF = false;
    53. while (true) {
    54. if (inOff >= inLimit) {
    55. // 读取一行数据,并返回这一行的实际读取大小
    56. inLimit = (inStream == null) ? reader.read(inCharBuf) : inStream.read(inByteBuf);
    57. inOff = 0;
    58. // 如果没有读取到数据,那么就直接结束读取操作
    59. if (inLimit <= 0) {
    60. // 如果当前长度为0或者是改行是注释,那么就返回-1。否则返回len的值。
    61. if (len == 0 || isCommentLine) {
    62. return -1;
    63. }
    64. return len;
    65. }
    66. }
    67. // 判断是根据字符流还是字节流读取当前字符
    68. if (inStream != null) {
    69. // The line below is equivalent to calling a ISO8859-1 decoder.
    70. // 字节流是根据ISO8859-1进行编码的,所以在这里进行解码操作。
    71. c = (char) (0xff & inByteBuf[inOff++]);
    72. } else {
    73. c = inCharBuf[inOff++];
    74. }
    75. // 如果前一个字符是换行符号,那么判断当前字符是否也是换行符号
    76. if (skipLF) {
    77. skipLF = false;
    78. if (c == '\n') {
    79. continue;
    80. }
    81. }
    82. // 如果前一个字符是空格,那么判断当前字符是不是空格类字符
    83. if (skipWhiteSpace) {
    84. if (c == ' ' || c == '\t' || c == '\f') {
    85. continue;
    86. }
    87. if (!appendedLineBegin && (c == '\r' || c == '\n')) {
    88. continue;
    89. }
    90. skipWhiteSpace = false;
    91. appendedLineBegin = false;
    92. }
    93. // 如果当前新的一行,那么进入该if判断中
    94. if (isNewLine) {
    95. isNewLine = false;
    96. // 如果当前字符是#或者是!,那么表示该行是一个注释行
    97. if (c == '#' || c == '!') {
    98. isCommentLine = true;
    99. continue;
    100. }
    101. }
    102. // 根据当前字符是不是换行符号进行判断操作
    103. if (c != '\n' && c != '\r') {
    104. // 当前字符不是换行符号
    105. lineBuf[len++] = c;// 将当前字符写入到行信息缓冲区中,并将len自增加1.
    106. // 如果len的长度大于行信息缓冲区的大小,那么对lineBuf进行扩容,扩容大小为原来的两倍,最大为Integer.MAX_VALUE
    107. if (len == lineBuf.length) {
    108. int newLength = lineBuf.length * 2;
    109. if (newLength < 0) {
    110. newLength = Integer.MAX_VALUE;
    111. }
    112. char[] buf = new char[newLength];
    113. System.arraycopy(lineBuf, 0, buf, 0, lineBuf.length);
    114. lineBuf = buf;
    115. }
    116. // 是否是转义字符
    117. // flip the preceding backslash flag
    118. if (c == '\') {
    119. precedingBackslash = !precedingBackslash;
    120. } else {
    121. precedingBackslash = false;
    122. }
    123. } else {
    124. // reached EOL
    125. if (isCommentLine || len == 0) {
    126. // 如果这一行是注释行,或者是当前长度为0,那么进行clean操作。
    127. isCommentLine = false;
    128. isNewLine = true;
    129. skipWhiteSpace = true;
    130. len = 0;
    131. continue;
    132. }
    133. // 如果已经没有数据了,就重新读取
    134. if (inOff >= inLimit) {
    135. inLimit = (inStream == null) ? reader.read(inCharBuf) : inStream.read(inByteBuf);
    136. inOff = 0;
    137. if (inLimit <= 0) {
    138. return len;
    139. }
    140. }
    141. // 查看是否是转义字符
    142. if (precedingBackslash) {
    143. // 如果是,那么表示是另起一行,进行属性的定义,len要自减少1.
    144. len -= 1;
    145. // skip the leading whitespace characters in following line
    146. skipWhiteSpace = true;
    147. appendedLineBegin = true;
    148. precedingBackslash = false;
    149. if (c == '\r') {
    150. skipLF = true;
    151. }
    152. } else {
    153. return len;
    154. }
    155. }
    156. }
    157. }
    158. }
    159. 复制代码
    • readLine这个方法每次读取一行数据;如果我们想在多行写数据,那么可以使用''来进行转义,在该转义符号后面换行,是被允许的。

    load0方法源码如下:

    1. private void load0(LineReader lr) throws IOException {
    2. char[] convtBuf = new char[1024];
    3. // 读取的字符总数
    4. int limit;
    5. // 当前key所在位置
    6. int keyLen;
    7. // value的起始位置
    8. int valueStart;
    9. // 当前字符
    10. char c;
    11. //
    12. boolean hasSep;
    13. // 是否是转义字符
    14. boolean precedingBackslash;
    15. while ((limit = lr.readLine()) >= 0) {
    16. c = 0;
    17. // key的长度
    18. keyLen = 0;
    19. // value的起始位置默认为limit
    20. valueStart = limit;
    21. //
    22. hasSep = false;
    23. precedingBackslash = false;
    24. // 如果key的长度小于总的字符长度,那么就进入循环
    25. while (keyLen < limit) {
    26. // 获取当前字符
    27. c = lr.lineBuf[keyLen];
    28. // 如果当前字符是=或者是:,而且前一个字符不是转义字符,那么就表示key的描述已经结束
    29. if ((c == '=' || c == ':') && !precedingBackslash) {
    30. // 指定value的起始位置为当前keyLen的下一个位置
    31. valueStart = keyLen + 1;
    32. // 并且指定,去除空格
    33. hasSep = true;
    34. break;
    35. } else if ((c == ' ' || c == '\t' || c == '\f') && !precedingBackslash) {
    36. // 如果当前字符是空格类字符,而且前一个字符不是转义字符,那么表示key的描述已经结束
    37. // 指定value的起始位置为当前位置的下一个位置
    38. valueStart = keyLen + 1;
    39. break;
    40. }
    41. // 如果当前字符为'',那么跟新是否是转义号。
    42. if (c == '\') {
    43. precedingBackslash = !precedingBackslash;
    44. } else {
    45. precedingBackslash = false;
    46. }
    47. keyLen++;
    48. }
    49. // 如果value的起始位置小于总的字符长度,那么就进入该循环
    50. while (valueStart < limit) {
    51. // 获取当前字符
    52. c = lr.lineBuf[valueStart];
    53. // 判断当前字符是否是空格类字符,达到去空格的效果
    54. if (c != ' ' && c != '\t' && c != '\f') {
    55. // 当前字符不是空格类字符,而且当前字符为=或者是:,并在此之前没有出现过=或者:字符。
    56. // 那么value的起始位置继续往后移动。
    57. if (!hasSep && (c == '=' || c == ':')) {
    58. hasSep = true;
    59. } else {
    60. // 当前字符不是=或者:,或者在此之前出现过=或者:字符。那么结束循环。
    61. break;
    62. }
    63. }
    64. valueStart++;
    65. }
    66. // 读取key
    67. String key = loadConvert(lr.lineBuf, 0, keyLen, convtBuf);
    68. // 读取value
    69. String value = loadConvert(lr.lineBuf, valueStart, limit - valueStart, convtBuf);
    70. // 包括key/value
    71. put(key, value);
    72. }
    73. }
    74. 复制代码
    • 会将分割符号两边的空格去掉,并且分割符号可以是=,:,空格等。而且=和:的级别比空格分隔符高,即当这两个都存在的情况下,是按照=/:分割的。可以看到在最后会调用一个loadConvert方法,该方法主要是做key/value的读取,并将十六进制的字符进行转换。

    总结

    本文阐述了Properties的基本作用以及源码实现,是不是对Properties有了更近一步的认识呢。

  • 相关阅读:
    MySQL索引
    嵌入式数据库Sqlite
    9.21
    Cause: compileSdkVersion is not specified. Please add it to build.gradle
    HTML标签学习
    大数据调度最佳实践 | 从Airflow迁移到Apache DolphinScheduler
    渗透测试基础 | 附带测试点、测试场景
    BI财务分析 – 反映盈利水平利润占比的指标如何分析(下)
    解决CSDN因版权不明而无法发布博客的问题
    【论文精读】TransE 及其实现
  • 原文地址:https://blog.csdn.net/m0_73311735/article/details/126869971