zoukankan      html  css  js  c++  java
  • Java 读写Properties配置文件

    1.Properties类与Properties配置文件

    什么是java的配置文件?  在Java中,其配置文件常为.properties文件,格式为文本文件,文件的内容的格式是“键=值”的格式,文本注释信息可以用"#"来注释。

    Properties类继承自Hashtable类并且实现了Map接口,也是使用一种键值对的形式来保存属性集。不过Properties有特殊的地方,就是它的键和值都是字符串类型。

    2.Properties中的主要方法

    1. getProperty / setProperty

       这两个方法是分别是获取和设置属性信息。

    2. clear (),清除所有装载的 键 - 值对。该方法在基类中提供。

    3. load ( InputStream inStream),从输入流中读取属性列表(键和元素对)。通过对指定的文件(比如说上面的 test.properties 文件)进行装载来获取该文件中的所有键 - 值对。以供 getProperty ( String key) 来搜索。

    4. store ( OutputStream out, String comments),将此 Properties 表中的属性列表(键和元素对)写入输出流。与 load 方法相反,该方法将键 - 值对写入到指定的文件中去。

    3. 编写读取.properties的两种方式

    //方式一:
    		File file = new File("aa.properties");
    		Properties pro = new Properties();
    		pro.setProperty("1", "张三");
    		pro.setProperty("2", "李四");
    		pro.store(new PrintStream(file), "utf-8");
    		pro.load(new FileInputStream(file));
    		
    		System.out.println(pro.getProperty("1"));
    		System.out.println(pro.getProperty("2"));
    

       

    //方式二:
    		File fi = new File("fil.properties");
    		Properties pro  = new Properties();
    		pro.put("1", "你的");
    		pro.put("2", "真的");
    		pro.store(new PrintStream(fi), "UTF-8");
    		pro.load(new FileInputStream(fi));
    		
    		System.out.println(pro.get("1"));
    		System.out.println(pro.get("2"));
    

     

  • 相关阅读:
    程序编译的四个阶段
    c++的符号表的肤浅认识
    git高级用法之cheery-pick
    rust 使用国内镜像,快速安装方法
    protobuf 的enum与string转换
    c++ 获取GMT 时间和字符串
    proto3 不支持内建类型的非空判断即 hasXXX
    cmake 中的 compile_commands.json 文件
    整数划分问题(记忆化搜索和DP方法)
    查找系列合集-二分查找
  • 原文地址:https://www.cnblogs.com/gshao/p/10217574.html
Copyright © 2011-2022 走看看