properties的使用

本文介绍如何利用Java的Properties类创建和读取配置文件,通过示例展示了如何将数据存储为.properties文件并从中读取数据,以此来灵活地管理程序中的初始化设置。

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

在程序中我们可能会遇到想要修改属性的某些初始化值时,一般的做法是修改代码里面的初始值,使用properties可以让我们不修改代码就可以实现修改初始值的功能.

properties的使用方法和HashMap的存储是一样的,都是通过key-value的方法,不同的是,会生成一个.properties的文件保存数据.

public static void main(String[] args) {

        // Property 属性  继承自Hashtable
        // Hashtable 和Hashmap是一样的
        // 区别在于Hashtable中key和value的值都不能为null,Hashmap可以

        Hashtable<String, String> ht = new Hashtable<String,String>();

        // ht.put(null, null); NullPointerException

        HashMap<String, String> ht1 = new HashMap<String,String>();

    }

创建一个properties文件

public class Test2 {

    public static void main(String[] args) {

        // 属性列表
        Properties properties = new Properties();
        properties.setProperty("name", "张三");
        properties.setProperty("age", "18");

        // 通过输出流保存到硬盘上
        // 相对路径,保存在工程目录下
        try (FileOutputStream fileOutputStream = new FileOutputStream("people.properties");){   
            properties.store(fileOutputStream, "Save info");
        } catch (FileNotFoundException e) {

            e.printStackTrace();
        } catch (IOException e) {

            e.printStackTrace();
        }
    }
}

从文件中读取

import java.io.FileInputStream;
import java.util.Properties;

public class Test3 {

    public static void main(String[] args) {

        // 通过key-value 的访问方式
        // 可以不通过修改程序获取不同的执行效果

        // 使用properties从配置文件中加载属性的值,可以随着文件的变化而变化
        Properties properties = new Properties();

        try (FileInputStream fileInputStream = new FileInputStream("people.properties");){

            // 从指定的流中加载数据
            properties.load(fileInputStream);

        } catch (Exception e) {

        }

        // 加载完毕,获取数据  根据key获取value
        String name = properties.getProperty("name");
        String age = properties.getProperty("age");
        String school = properties.getProperty("school");   
        System.out.println(name + age + school);

    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值