Properties类读取配置文件

前言

Properties类的介绍 :

在Java中提供了 java.util.Properties 类,来读取 .properties 属性文件。在程序调用 Properties 类的 load() 方法时,系统把 .properties 属性文件的内容加载到内存中。因为 Properties 类继承了 Hashtable 类,Properties 类把“=”之间的内容,添加到Hashtable 对象的 key 值,并同时添加 key 值对应的 value 值,也就是“=”右侧的值。所有在编写 .properties 属性文件时一定要用“=”号把名称与值分隔开。
通过 .properties 属性文形式只能保存 String 类型信息。
Properties 类是线程安全的,多个线程可以共享一个Properties对象,而不需要外部同步。

Properties官方api


一、Properties类的使用 :

1、创建sk.properties文件

在项目的默认路径(src目录)下创建 sk.properties 属性文件(名称可以自定义,扩展名必须为 properties )。

name=Jack
gender=male

2、编写读取 properties 属性文件,并输出属性值。


	//从配置文件获取密钥信息
	private static final Properties properties = getProperties();

	private static String getProperties(){
        Properties properties = new Properties();
        try {
        	//生产环境根目录
            properties.load(new FileInputStream(System.getProperty("user.dir").concat("/sk.properties")));
            //本地测试
//            properties.load(new FileInputStream(("src/main/resources/sk.properties")));
        } catch (IOException e) {
            e.printStackTrace();
        }
        return properties.getProperty("vehLocationPartitions");
    }

	public void test(){
		String name=properties.getProperty("name");
        String gender=properties.getProperty("gender");
        // 输出结果
        System.out.println("name: "+name);
        System.out.println("gender: "+gender);
	}

3、运行结果

name: Jack
gender: male


总结

如果此篇文章有帮助到您, 希望打大佬们能关注点赞收藏评论支持一波,非常感谢大家!
如果有不对的地方请指正!!!

参考1
参考2

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

lfwh

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

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

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

打赏作者

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

抵扣说明:

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

余额充值