How to parse project properties or how to parse files with key-value pair

本文详细解析了如何使用 Java 的 Properties 类来解析包含应用配置信息的项目属性文件,并介绍了通过线程上下文类加载器加载资源的方法。讨论了类加载器在不同场景下的作用以及如何在不依赖自身类加载器的情况下加载资源。

If a file has content like

app.enabled = false
app.host = "localhost"
app.port = 8080
app.zoneId = "zone_id"
app.fulOpId = "test_uk_1"

which are all key-value pairs, we could use properties.load() to parse it.

    public static Properties loadProperties() {
        Properties properties = new Properties();
        try {
            InputStream in = Thread.currentThread().getContextClassLoader().getResourceAsStream("project.properties");
            if(in==null) {
                logger.warn("The project.properties file does not exist");
            } else {
                properties.load(in);
            }
        } catch(Exception e) {
            logger.error("Unable to read the project.properties", e);
        }
        return properties;
    }

 The reason to use Thread.currentThread().getContextClassLoader().getResourceAsStream("project.properties") and why it is different from normal class loader:

Each class will use its own classloader to load other classes. So if ClassA.class references ClassB.class then ClassB needs to be on the classpath of the classloader of ClassA, or its parents.

The thread context classloader is the current classloader for the current thread. An object can be created from a class in ClassLoaderC and then passed to a thread owned by ClassLoaderD. In this case the object needs to use Thread.currentThread().getContextClassLoader() directly if it wants to load resources that are not available on its own classloader.

 

转载于:https://www.cnblogs.com/codingforum/p/java.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值