Properties存取配置文件

本文介绍Java中Properties类的使用方法,包括如何加载和保存配置文件、设置和获取键值对等。通过示例代码展示了如何操作Properties对象进行数据读写。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

/*Properties存取配置文件
Properties是hashtable的子类。
也就是说它具备map集合的特点。而且它里面存储的键值对都是字符串

是集合中和IO技术相结合的集合容器。
该对象的特点:可以用于键值对形式的配置文件。
那么在加载数据时,需要数据有固定格式:键=值
*/
import java.io.*;//IO流
import java.util.*;//集合

class  PropertiesDemo
{
    public static void main(String[] args) throws IOException
    {       
        loadDemo();
    }

    public static void loadDemo() throws IOException
    {
        Properties prop = new Properties();//属性对象
        FileInputStream fis = new FileInputStream("info.txt");//文件输入流

        //将流中的数据加载进集合
        prop.load(fis);//load(),加载,参数可以放IO流

        prop.setProperty("wangwu","39");//修改内存

        FileOutputStream fos = new FileOutputStream("info.txt");//文件输出流
        prop.store(fos,"haha");//修改硬盘文件

        fos.close();
        fis.close();
        //System.out.println(prop);
        //prop.list(System.out);//list()列表输出,参数可以放PrintStream
    }
    //演示,如何将流中的数据存储到集合中。
    //想要将info.txt中键值数据存到集合中进行操作。
    /*
            1,用一个流和info.txt文件关联
            2,读取一行数据,将该行数据用“="进行切割
            3,等号左边作为键,右边作为值。存入到Properties集合中即可。
    */
    public static void method_1() throws IOException
    {
        BufferedReader bufr = new BufferedReader(new FileReader("info.txt"));
        String line = null;
        Properties prop = new Properties();
        while((line= bufr.readLine())!=null)
        {
            String[] arr = line.split("=");//split()切割,用“="进行切割,存放到String[] arr
            //System.out.println(arr[0]+".."+arr[1]);
            prop.setProperty(arr[0],arr[1]);//Properties成对存入,存入到Properties集合,调用 Hashtable 的方法 put。
        }
        bufr.close();
        System.out.println(prop);
    }

    //设置和获取元素
    public static void setAndGet()
    {
        Properties prop = new Properties();
        prop.setProperty("zhangsan","30");//setProperty(String key, String value) 调用 Hashtable 的方法 put。
        prop.setProperty("lisi","39");

//      System.out.println(prop);
        String value = prop.getProperty("lisi");//getProperty(String key) , 用指定的键在此属性列表中搜索key属性,返回value。
        System.out.println(value);

        Set<String> names = prop.stringProperyNames();//返回此属性列表中的键集,其中该键及其对应值是字符串
        for (String s :names )
        {
            System.out.println( s+":"+getProperty(s));//S是KEY,返回VALUE
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值