什么是Properties类
- Java中的类Properties(Java.util.Properties),主要用于读取java的配置文件。
- 在Java中,其配置文件常为.properties文件,格式为文本文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释。
- Properties类继承自Hashtable,而哈希表则是链表加数组的结构。
-
Properties类中常见的方法
- getProperty ( String key),进行在文本文档中搜索也就是通过参数 key ,得到 key 所对应的 value。
- load ( InputStream inStream),从输入流中读取属性列表(键和元素对)。通过对指定的文件,进行装载来获取该文件中的所有键 值对。以供 getProperty ( String key) 来搜索。
- setProperty ( String key, String value) ,调用 Hashtable 的方法 put 。他通过调用基类的put方法来设置 键 - 值对。
- store ( OutputStream out, String comments),以适合使用 load 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对通过输出流写入到指定的文件中去。(特别的是 String comments是标注会以#后来呈现)
- clear (),清除所有装载的 键 - 值对。该方法在基类中提供。
-
如何读取Properties文件
-
通常通过BufferedInputStream中FileInputStream传入Properties文件。
-
以下是通过 BufferedInputStream和BufferedOutputStream分别读取和写入Properties文件,并且通过Load方法以及Store方法来载入和写出Properties文件。
-
package com.my.hyz4; import java.io.BufferedInputStream; import java.io.BufferedOutputStream; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.util.Properties; public class Demo03 { public static void main(String[] args) { try (BufferedInputStream bis = new BufferedInputStream(new FileInputStream("d:\\tupian\\hba.properties"))) { Properties prpos = new Properties(); prpos.load(bis); System.out.println(prpos.get("aa")); System.out.println(prpos.size()); } catch (IOException e) { e.printStackTrace(); } //输出流负责写文件 Properties properties = new Properties(); properties.putIfAbsent("F1", "11111"); properties.putIfAbsent("F2", "21111"); properties.putIfAbsent("F3", "31111"); properties.putIfAbsent("F4", "41111"); try (//使用输出流,将Properties中的KV键值对写入文件当中 BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream("d:\\tupian\\rng.properties"))) { properties.store(bos, "just do it"); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }