java 代码静态块读取配置常用方法

本文介绍了两种在Java中读取属性文件的方法:使用Properties类和ResourceBundle。通过Properties类可以方便地加载和读取.properties文件,而ResourceBundle则适用于国际化资源的读取。

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

第一种:通过Properties读取

package study.utils;
 
import java.io.IOException;
import java.util.Properties;
 
public class PropertyUntil{
    private static Properties properties;
    
    private static void setProperty(){
        if (properties==null) {
            properties = new Properties();
            ClassLoader loader = Thread.currentThread().getContextClassLoader();
            try {
                properties.load(loader.getResourceAsStream("test.properties"));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    public static String getPropertiesKey(String key){
        if (properties==null) {
            setProperty();
        }
        return properties.getProperty(key, "default");
    }
}

 public static void main(String[] args) {
        System.out.println(getPropertiesKey("test"));
    }

 

第二种:通过ResourceBundle来读取

public static String test = "";

    static {
        ResourceBundle bundle = ResourceBundle.getBundle("test");//配置文件名称,不能带后缀文件类型
        test = bundle.getString("test");//配置文件中的key=value
    }

    public static void main(String[] args) {
        System.out.println(test);
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值