【JAVA】properties配置文件

参考地址

properties

是一种后缀为.properties的文本文件,在Java中常被用作配置文件,文件的内容格式是“键=值”的格式,可以用“#”作为注释

示例:存数据库的连接字符串

driver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/user
user=root
password=123456

Properties类

  • 存在于Java.util.Properties包下
  • 是Java中用来处理properties文件的类

常用方法

  • setProperty(String key, String value) 调用 Hashtable 的方法 put。

  • store(OutputStream out, String comments)
    以适合使用 load(InputStream) 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。

  • store(Writer writer, String comments)
    以适合使用 load(Reader) 方法的格式,将此 Properties 表中的属性列表(键和元素对)写入输出字符。

public class PropertiesTest {
  @Test
  public void propertiesTest(){
      //实例化一个Properties对象
      Properties pros = new Properties();
      // try catch 异常处理 
      try {
          //写入文件
          FileOutputStream fos = new FileOutputStream("test1.properties");
          //引入Writer,明确写入配置文件的编码,避免中文乱码使用utf-8
          OutputStreamWriter ops = new OutputStreamWriter(fos,"utf-8");
          //将需要写入的属性内容通过setProperty方法,存入properties对象中
          pros.setProperty("test","123");
          //调用存储方法store
          pros.store(ops,"测试数据");
          //关闭资源
          ops.close();
          fos.close();
      } catch (FileNotFoundException e) {
          e.printStackTrace();
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      } catch (IOException e) {
          e.printStackTrace();
      }
  }
}
  • load(InputStream inStream) 从输入流中读取属性列表(键和元素对)。
  • load(Reader reader) 按简单的面向行的格式从输入字符流中读取属性列表(键和元素对)
  • getProperty(String key) 用指定的键在此属性列表中搜索属性
  • getProperty(String key, String defaultValue) 用指定的键在属性列表中搜索属性。
public class getPropertiesTest {
@Test
public void propertiesTest(){
      //读取文件
      File file = new File("day04-02/src/hello.properties");
      System.out.println(file.exists());
      FileInputStream fis = new FileInputStream(file);
      //实例化Properties类
      Properties p  = new Properties();
      // 读取列表
      p.load(fis);

      //枚举器(Hashtable  Vector) 迭代器
      Enumeration<Object> keys = p.keys();
      while (keys.hasMoreElements()){
          String key = (String) keys.nextElement();
          System.out.println(key + " = " + p.getProperty(key) );
      }

}
}
  • storeToXML(OutputStream os, String comment) 发出一个表示此表中包含的所有属性的 XML 文档。
  • storeToXML(OutputStream os, String comment, String encoding)使用指定的编码发出一个表示此表中包含的所有属性的 XML 文档。
  • loadFromXML(InputStream in) 将指定输入流中由 XML 文档所表示的所有属性加载到此属性表中。

posted @ 2022-07-01 17:11  Phoenixy  阅读(2401)  评论(0)    收藏  举报