Properties持久的属性集

来源:互联网 发布:知乎热门话题 编辑:程序博客网 时间:2024/06/03 06:43

Properties 属性集合继承了Hashtable

属性包括属性名和属性值(键值对key==value)

作用

  • 可以存储多个键值,与map相似
  • 可以把键值对存储到文件中
  • 可以把文件中的键值对读取到Properties对象中

构造方法:
Properties() 创建一个无默认值的空属性列表。
成员方法:

  • String getProperty(String key) 用指定的键在此属性列表中搜索属性。
  • String getProperty(String key, String defaultValue) 用指定的键在属性列表中搜索属性。
  • void load(InputStream inStream) 从输入流中读取属性列表(键和元素对)。
  • void store(OutputStream out, String comments) 以适合使用 load(InputStream) 方法加载到 Properties 表中的格式,将此 Properties 表中的属性列表(键和元素对)写入输出流。comments是注释的内容
  • Object setProperty(String key, String value) 调用 Hashtable 的方法 put。添加键值对的方法,和map的put方法类似。

    import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileWriter;import java.io.IOException;import java.util.Properties;public class PropertiesDemo {public static void main(String[] args) throws IOException {    Properties pros = new Properties();    read(pros);}public static void read(Properties pros) throws IOException, FileNotFoundException {    pros.load(new FileInputStream("a.properties"));    System.out.println(pros.get("哈哈哈"));    System.out.println(pros);    System.out.println("输入成功");}public static Properties add() throws FileNotFoundException, IOException {    //创建一个空的属性列表    Properties pros=new Properties();    System.out.println(pros);    //添加键值对    pros.setProperty("哈哈哈", "呵呵呵");    pros.setProperty("喔喔", "方法");    pros.setProperty("宿舍的", "付款");    //通过key 来获取值    String value1 = pros.getProperty("哈哈哈");    String value2 = pros.getProperty("喔喔");    System.out.println(value1);    System.out.println(value2);    //将properties写入到文件中    FileOutputStream fos=new FileOutputStream("a.properties");    pros.store(fos, "我是注释     comments");    return pros;    } }
原创粉丝点击