Properties持久的属性集

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;
    
        }
     }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

古月_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值